gpt4 book ai didi

c++ - 使用 getline 拆分字符串并检查 int

转载 作者:行者123 更新时间:2023-11-30 04:20:04 25 4
gpt4 key购买 nike

我有一个文件:

name1 8
name2 27
name3 6

然后我将其解析为 vector 。这是我的代码:

  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();
}

最佳答案

如果 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();
}
// ...

关于c++ - 使用 getline 拆分字符串并检查 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15418906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com