How can i check if the user inputs only 0-9 digits? - exception

When the user enters a character it's converted into a integer.
I need the ibans array with only 0-9 digits.
How can i use try-catch?
Can i use more formal functions?
I tried and it didn't work:
int* create_iban() throw(){
int* ibans = new int[16]{};
int i=0;
cout << "Digit your custom IBAN: ";
do{
cin>>ibans[i];
if(!(isdigit(ibans[i])))
throw "No digit entered!";
i++;
} while(i<16);
return ibans;
}
int main(){
try{
create_iban();
} catch(const char* ex){
cout << ex << endl;
}
}

Related

Check special character in string array using isalpha

So I am trying to take words from a file and save them into a dynamic array, and then print the array sorted alphabetically along with the concordance of each word in the array. I am facing a problem in identifying special characters/ numbers and deleting them from the array. I want to use the isalpha function as it is in the assignment prompt. When I run my code, it works perfectly but special characters and numbers are not eliminated from the array. Any idea on how to do this using isalpha?
#include <iostream>
#include <stream>
#include <iomanip>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <string>
using namespace std;
void loadData();
void checkSpecialCharacters(string wordPtr, int size);
void alphabeticalSort(string *wordPtr, int size);
void frequencyCounter(string *wordptr, int size);
int main()
{
loadData();
return 0;
}
void loadData()
{
string fileName;
cout << "This program processes any text file to give you the concordance for each word present, and how many times it appears in the file." << endl;
cout << "Please enter the name of the text file you want to process followed by '.txt': " << endl;
cin >> fileName;
ifstream dataFile(fileName);
if (dataFile.fail())
{
cerr << fileName << " could not be opened." << endl; //error message if file opening fails
exit(-1);
}
string word;
int size = 0;
while (dataFile >> word)
{
size++;
}
dataFile.clear();
dataFile.seekg(0);
string* wordPtr = new string[size];
int ctr = 0;
for (int i = 0; i < size; i++)
{
dataFile >> wordPtr[i];
checkSpecialCharacters(wordPtr[i], size);
std::transform(wordPtr[i].begin(), wordPtr[i].end(), wordPtr[i].begin(), ::tolower);
cout << wordPtr[i] << endl;
}
dataFile.close();
alphabeticalSort(wordPtr, size);
frequencyCounter(wordPtr, size);
delete[] wordPtr;
}
void checkSpecialCharacters(string wordPtr, int size)
{
for (int i = 0; i < size; i++)
{
if (isalpha(wordPtr[i]) == true)
{
for (int j = 0; j < size; j++)
{
wordPtr[j] = wordPtr[j + 1];
cout << wordPtr[j];
}
}
}
}
void alphabeticalSort(string *wordPtr, int size)
{
int i, j;
string temp; //temporary holding variable
for (i = 0; i < (size - 1); i++)
{
for (j = 0; j < (size - 1); j++)
{
if ((wordPtr[j])>(wordPtr[j + 1]))
{
temp = wordPtr[j];
wordPtr[j] = wordPtr[j + 1];
wordPtr[j + 1] = temp;
}
}
}
}
void frequencyCounter(string *wordPtr, int size)
{
string finalFileName;
cout << "Please enter the name of the file that you want to store the concordance in followed by .txt: " << endl;
cin >> finalFileName;
ofstream concordanceFile(finalFileName, ios::out);
if (concordanceFile.fail())
{
cerr << finalFileName << " could not be opened." << endl;
exit(-1);
}
int frequency = 1;
int index = 1;
string element = wordPtr[0];
while (index < size)
{
if (wordPtr[index - 1] == wordPtr[index]) // check if element is equal to previous element
{
frequency++;
index++;
}
else
{
concordanceFile.setf(ios::left);
concordanceFile << setw(10) << element << " " << setw(10) << frequency << endl;
cout.setf(ios::left);
cout << setw(10) << element << " " << setw(10) << frequency << endl;
element = wordPtr[index];
index++;
frequency = 1; //reset frequency
}
}
cout << "Concordance data saved in " << finalFileName << " successfully!" << endl;
}

In the output first the text " Sum is : " is getting printed and then the function is getting called. Please check this code

#include<iostream>
using namespace std;
int sum();
int main() {
cout << "Sum is: " << sum() << endl;
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
return (num1 + num2);
}
I am not getting a correct out put. First "Sum is: " getting called and then the function in output.
Output is given as:- "Sum is: Enter 2 numbers: " and then enter numbers. But it gives correct output. But its not coming as I want.
Your sum() function gives the "Enter 2 numbers: " output, so when you call that function after your main() gives the output "Sum is: ", it is clear that the complete output is "Sum is: Enter 2 numbers: ".
You need to rewrite your code (especially the function sum()) to get the output in the order you want it to be.
Example:
#include<iostream>
using namespace std;
int sum();
int main() {
sum();
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
cout << "Your sum is: " << (num1+num2) << endl;
return 0;
}
You're not getting "Enter 2 numbers" first because in the main function this line is called first.
cout << "Sum is: " << sum() << endl;
which is equivalent to
cout << "Sum is:";
cout << sum();
cout << endl;
The first line prints
Sum is:
To the standard output and then it calls the function sum()
which prints Enter 2 numbers:
So the standard output is:
Sum is:
Enter 2 numbers:
Then the function returns and you get the result and the newline.
To change this either take the input in the main function or just take the return value of the function in a variable;
#include<iostream>
using namespace std;
int sum();
int main() {
int s = sum;
cout << "Your sum is: " << s << endl;
return 0;
}
int sum() {
int num1,num2;
cout << "Enter 2 numbers: " << endl;
cin >> num1 >> num2;
return (num1 + num2);
}

std::for_each and std::vector destructor call

I have the following problem with std::for_each and a functor proxy object.
See the following code:
struct Functor {
std::vector<int> data;
const unsigned mID;
static unsigned id;
Functor() : mID(id++) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}
~Functor() {
std::cout << "Functor dtor: " << mID << std::endl;
}
void operator() (int i) {
std::cout << "Functor print: " << i << std::endl;
data.push_back(i);
std::cout << "Dump: ";
for(int i = 0; i < data.size(); ++i)
std::cout << data[i] << " ";
std::cout << std::endl;
}
};
unsigned Functor::id = 0;
From above, the proxy object simply does 2 things, it prints the data out to the CMD and it stores a copy for itself to use. Below is the example use case of the object:
int main () {
std::vector<int> intvec;
for(int i = 0; i < 10; ++i)
intvec.push_back(i);
Functor myfunctor;
std::for_each(intvec.begin(), intvec.end(), myfunctor);
std::cout << "Data in my functor: " << myfunctor.data.size() << std::endl;
for(int i = 0; i < myfunctor.data.size(); ++i)
std::cout << "myfunctor data: " << myfunctor.data[i] << std::endl;
return 0;
}
This is the part it gets really fishy for me. The output generated is that my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Also as a result of the destructor being called at the end of the std::for_each, the Functor.data is empty as well!
Is there a way to make sure data inside Functor is kept persistent? I wish to keep track of the state of my functor when used inside functions such as std::for_each (Basically any given std algorithm function that can take in a unary functor)
Do note that I am using c++03 ONLY. Many thanks.
[...] my functor proxy object is constructed once but deconstructed three times! Something is bypassing the construction call.
Not quite. Your class is default-constructed once, but is also copy-constructed twice. You don't log the copy construction, so it doesn't show up on your output.
If you add a logging copy constructor, you'll see "Functor constructed with id: 0" printed three times:
Functor(const Functor& other) : mID(other.mID) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}

C++ - Exception handling

I'm learning exception handling in C++. Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
class point{
private:
float x, y;
public:
enum Error{
negative_coordinates,
};
point();
point(float, float);
~point();
float return_x();
float return_y();
};
point::point(){
}
point::point(float a, float b){
if(x < 0 && y < 0){
throw negative_coordinates;
}
else{
x = a;
y = b;
}
}
point::~point(){
}
float point::return_x(){
return x;
}
float point::return_y(){
return y;
}
int main()
{
try{
float x, y;
cout << "Enter coordinates of some point: " << endl;
cin >> x >> y;
if(x < 0 && y < 0){
throw (0);
}
}
catch(point::Error e){
const char * message [] = {"You entered negative coordinates"};
cout << "" << message[e] << endl;
}
}
If I put two negative values I got this:
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Process returned 3 (0x3) execution time : 5.420 s
Press any key to continue.
Any idea?
You throw an 'int' when you enter two negative values, but you catch a point. The types of your throw and catch need to be the same. If I change: catch(point::Error e) to catch(int e), the program runs fine.
As per: http://www.cplusplus.com/doc/tutorial/exceptions/

non-portable way to find exception type in catch (...) for g++

Related questions:
Determining exception type after the exception is caught?
How can I determine the current exception in a catch (...) block?
This question differs because I don't care about portability. I'm interested in code specifically for g++ or perhaps even specific versions of g++ (4.6.3). It will not be used in production.
I'm dealing with legacy code that has thousands of throw statements with perhaps hundreds of thrown types. This code runs on nearly 1000 machines and catches about 40 throws per day. It is not repeatable.
At the outside layer, I can do a try { /.../ } catch (...) { /* caught it */ } and see that an exception was thrown. But I have not been able to find the type of the exception, let alone the location it is thrown from.
I believe the information must be available because code like the following works and prints "Y":
#include <iostream>
using namespace std;
struct X {};
struct Y {};
struct Z {};
int main(int, char **) {
try {
//...
throw Y();
//...
} catch (...) {
cout << "Caught unknown" << endl;
try {
throw;
} catch (const X &x) {
cout << "X" << endl;
} catch (const Y &y) {
cout << "Y" << endl;
} catch (const Z &z) {
cout << "Z" << endl;
}
}
}
Are there any [non-portable|dirty|nasty|ugly]* tricks to identify the exception type under g++ in a catch (...)?
Here's what I use:
#include <cxxabi.h>
using std::string;
string deMangle(const char* const name)
{
int status = -1;
char* const dem = __cxxabiv1::__cxa_demangle(name, 0, 0, &status);
const string ret = status == 0 ? dem : name;
if (status == 0)
free(dem);
return ret;
}
string getGenericExceptionInfo()
{
const std::type_info* t = __cxxabiv1::__cxa_current_exception_type();
char const* name = t->name();
return deMangle(name);
}
Usage:
catch (...)
{
std::cerr << "caught: " << getGenericExceptionInfo() << std::endl;
}