c_plusplus_beginner
c_plusplus_beginner

Reputation: 21

C++ convert string to int if numeric, else return 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
        }
    }

Upvotes: 0

Views: 536

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76436

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.

Upvotes: 1

Related Questions