【问题标题】:Use getline to split a string and check for int使用 getline 拆分字符串并检查 int
【发布时间】:2013-03-03 08:53:48
【问题描述】:

我有一个文件:

name1 8
name2 27
name3 6

我将它解析成向量。这是我的代码:

  int i=0;
  vector<Student> stud;

  string line;
  ifstream myfile1(myfile);
  if (!myfile1.is_open()) {return false;}
  else {
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name >> stud[i].Grade1;
      i++;
    }
    myfile1.close();
  }

我需要检查 stud[i].Grade1 是否为 int。如果不是,则返回 false。 文件可以包含:

name1 haha
name2 27
name3 6

我该怎么做?

编辑:

我尝试了另一种方法(没有 getline),它似乎有效。我不明白为什么:/

int i=0;
vector<Student> stud;

ifstream myfile1(myfile);
if (!myfile1.is_open()) {return false;}
else {
  stud.push_back(Student());
  while( myfile1 >> stud[i].Name ) {
    if(!(myfile1 >> stud[i].Points1)) return false;
    i++;
    stud.push_back(Student());
}
myfile1.close();
}

【问题讨论】:

标签: c++ parsing vector getline


【解决方案1】:

如果Grade1 的类型为数字,例如int,则使用std::istringstream::fail()

// ...
    while( getline(myfile1, line) ) {
      istringstream iss(line);
      stud.push_back(Student());
      iss >> stud[i].Name;
      iss >> stud[i].Grade1;
      if (iss.fail())
        return false;
      i++;
    }
    myfile1.close();
  }
// ...

【讨论】:

  • 我之前试过,但总是返回false。即使有数字。
  • Grade1 的类型是什么?
  • 这是整数。结构代码:struct Student { string Name; int Grade1, Grade2; //学生(字符串名称,int Grade1,int Grade2); };
  • 如您所见,我在两个单独的语句中使用iss &gt;&gt; ...,我认为这很重要。测试我的代码。
  • 啊,对不起,我没看到。有用!谢谢。但是如果我有 line: name4 27d 我忘了说,必须只有数字。
【解决方案2】:

它可能看起来像这样:

std::vector<Student> students;
std::ifstream myfile1(myfile);
if (!myfile1.is_open())
    return false;

std::string line;
while (std::getline(myfile1, line))
{
    // skip empty lines:
    if (line.empty()) continue;

    Student s;
    std::istringstream iss(line);
    if (!(iss >> s.Name))
        return false;
    if (!(iss >> s.Grade1))
        return false;

    students.push_back(s);
}

请注意iss &gt;&gt; s.Grade1 不仅适用于十进制,而且适用于八进制和十六进制数。为了确保只读取十进制值,您可以将其读入临时std::string 对象并在使用它检索数字之前对其进行验证。看看How to determine if a string is a number with C++?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多