繁体   English   中英

从 ifstream 中识别 String 或 Int

[英]Identifying String or Int from ifstream

我试图确定来自 ifstream 的输入是 int 还是 C++11 中的字符串。 ifstream 将给出一个字符串或一个整数,我需要为每个做不同的事情。 如果它是一个 int,我需要使用前两个作为二维数组中的位置,第三个作为值。 如果它是一个字符串,我需要创建一个 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++;
  }

我尝试了 isdigit 和几种不同类型的转换,但它们没有奏效。 它一直认为字符串中的数字不是 int。

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

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

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

一个例子: https://ideone.com/g4YkOU

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM