My code asks user to enter coordinates and if the input is q, the program stops and otherwise, it checks if the input is numeric.
If x and y are both numeric, stoi_with_check converts them from string to int. This is because later I need to use coordinates as int when making a matrix.
If x or y is not numeric, stoi_with_check returns 0.
On lines 44 and 45, I'm not sure how this stoi_with_check function should be used, if I want to check both strings, x and y.
Thanks for your help.
#include <iostream>
#include <string.h>
using namespace std;
unsigned int stoi_with_check(const string& str) // if numeric -> convert string to int, if not numeric -> return 0
{
bool is_numeric = true;
for(unsigned int i = 0; i < str.length(); ++i)
{
if(not isdigit(str.at(i)))
{
is_numeric = false;
break;
}
}
if(is_numeric)
{
return stoi(str);
}
else
{
return 0;
}
}
int main()
{
string x, y;
while (true) {
cout << "Enter coordinates (x, y): ";
cin >> x;
if (x == "q" or x == "Q") {
cout << "Quitting" << endl;
exit(0);
}
cin >> y;
// x and y are now strings
// Next convert them to ints if they are numeric
// If they are not numeric, return value 0
stoi_with_check(x);
stoi_with_check(y);
// next print board by using int x and int y
}
}
int ix, iy;to do that.try { return std::stoi(str); } catch( const std::exception&) { return 0; }.for (unsigned i = 0; ii < str.length(); ++i) if (!isdigit(str[i])) return 0;is much clearer. For several reasons.