DLorentz
DLorentz

Reputation: 13

Identifying String or Int from ifstream

I'm trying to identify whether an input from a ifstream is an int or a string in C++11. the ifstream will give either a string or an int and I need to do different things for each. If it's an int, I need to use the first two as locations in a 2d array with the third as the value. If its a string, I need to create a NodeData object.

   for (;;) {

  int n1, n2, n3;
  string s1;
  infile >> s1;
  //trying isdigit and casting string to int
  if (isdigit( stoi(s1.c_str()))) {
     //check if last 2 ints exist
     if ((infile >> n2 >> n3)) {
        n1 = stoi(s1);
        //end of input check
        if (n1 == 0) {
           break;
        }

        C[n1][n2] = n3;
     }
  }
  else {
     NodeData temp = NodeData(s1);
     data[size] = temp;
     size++;
  }

} I have tried isdigit and several different types of casting but they haven't worked. It keeps thinking the number in the string is not an int when it is.

Upvotes: 1

Views: 64

Answers (2)

mch
mch

Reputation: 9804

You can write directly to an int and check the returned value of the operation:

if (infile >> in1)
{
    //in1 contains the int
}
else if (infile >> s1)
{
    //s1 contains the string
}

an example: https://ideone.com/g4YkOU

Upvotes: 1

Lukas-T
Lukas-T

Reputation: 11340

isdigit(ch) will just check if the given parameter ch can be considered a digit (e.g. if '0' <= ch <= '9' for most languages).

stoi will cause an exception if you call it with a string that does not represent a number. So you could use try/catch here:

string s1;
int i1;
bool isInt;
infile >> s1;

try {
    i1 = std::stoi(s1);
    isInt = true;
    // s1 was successfully parsed as a string -> use as int.
}
catch(const std::exception &) {
    isInt = false;
    // now we know that s1 could not be parsed as an int -> use as string.
}

Upvotes: 1

Related Questions