从ifstream

时间:2019-10-24 12:16:13

标签: c++ c++11

我正在尝试识别来自ifstream的输入是C ++ 11中的int还是字符串。 ifstream将给出一个字符串或一个int,我需要为每个做不同的事情。如果是整数,则需要将前两个用作2d数组中的位置,第三个作为值。如果它是字符串,则需要创建一个NodeData对象。

   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++;
  }

} 我尝试过isdigit和几种不同类型的转换,但是它们没有用。它一直认为字符串中的数字不是整数。

2 个答案:

答案 0 :(得分:1)

isdigit(ch)只会检查给定的参数ch是否可以视为数字(例如,对于大多数语言来说,'0' <= ch <= '9'是否适用)。

如果

stoi使用不代表数字的字符串调用它将引起异常。因此,您可以在此处使用try / catch:

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.
}

答案 1 :(得分:1)

您可以直接写入int并检查操作的返回值:

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

示例:https://ideone.com/g4YkOU

相关问题