For my homework, I am using std::istringstream
in order to create error messages when applicable.
My program works fine, except for two certain cases, it does not work properly.
The first test case is when the second number is zero and the first number is a number greater than zero.
The second test case is when the second number, n
, is greater than the first number, m
.
It should return the error message when n > m
, but it goes straight to the result.
My question is, how exactly does std:::istringstream
work? How does it compare the value in argv
at this line? How can I fix my code so it checks the correct thing?
More specifically, what does this line do?
(!(iss >> m))
My teacher gave us this std::istringstream
code in an earlier lab, however I believe that it is checking for only positive numbers, which is why it fails in the first test case I included. How can I fix this?
int main(int argc, char* argv[])
{
unsigned int m;
unsigned int n;
//error checks
istringstream iss;
if(argc != 3) {
cerr<< "Usage: " << argv[0] << " <integer m> <integer n>" << endl;
return 1;
}
iss.str(argv[1]);
if (!(iss >> m) ){
cerr << "Error: The first argument is not a valid nonnegative integer." << endl;
return 1;
}
iss.clear();
iss.str(argv[2]);
if (!(iss >> n) ){
cerr << "Error: The second argument is not a valid nonnegative integer." << endl;
return 1;
}
if (n > m){
cerr << "Error: The second argument is not a valid nonnegative integer." << endl;
return 1;
}
//correct output
cout << m << " x " << n << " = " << russian_peasant_multiplication(m, n) << endl;
return 0;
}