0

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
        }
    }
3
  • You never store the result of these function calls? Just use another set of variables int ix, iy; to do that. Commented Aug 17, 2022 at 10:25
  • 1
    Use the fact that std::stoi's can throw exceptions : en.cppreference.com/w/cpp/string/basic_string/stol. Thus : try { return std::stoi(str); } catch( const std::exception&) { return 0; } . Commented Aug 17, 2022 at 10:32
  • A tip on style: for (unsigned i = 0; ii < str.length(); ++i) if (!isdigit(str[i])) return 0; is much clearer. For several reasons. Commented Aug 17, 2022 at 12:39

1 Answer 1

1

This is how you could do it:

int X = stoi_with_check(x);
int Y = stoi_with_check(y);

if (X && Y) { //None of them is 0
    //Do your stuff
}

Basically you store your would-be-coordinates and if they are valid, process them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.