C++只读 fstream 中的整数
如何读取文件并忽略非整数? 我有从文件中删除“,”的部分,但也需要删除第一个单词。
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
以上是我正在使用的所有STL。
string line, data;
int num;
bool IN = false;
ifstream file;
file.open(filename);
if (!file)
{
cout << "File is not loading" << endl;
return;
}
while (getline(file, line))
{
stringstream ss(line);
while (getline(ss, data, ','))
{
if (!stoi(data))
{
break;
}
else
{
num = stoi(data);
if (IN == false)
{
//h(num);
//IN = true;
}
}
}
}
我试图读取的文件
3
Andrew A,0,1
Jason B,2,1
Joseph C,3,0
基本上,我可以完全忽略这些名称。我只需要数字
How do I read in a file and ignore nonintegers?
I have the part down where I remove the ',' from the file, but also need to remove the first word as well.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
above is all the STL I am using.
string line, data;
int num;
bool IN = false;
ifstream file;
file.open(filename);
if (!file)
{
cout << "File is not loading" << endl;
return;
}
while (getline(file, line))
{
stringstream ss(line);
while (getline(ss, data, ','))
{
if (!stoi(data))
{
break;
}
else
{
num = stoi(data);
if (IN == false)
{
//h(num);
//IN = true;
}
}
}
}
The file I am trying to read from is
3
Andrew A,0,1
Jason B,2,1
Joseph C,3,0
Basically, I am able to just completely ignore the names. I just need the numbers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经知道如何逐行阅读,并根据逗号将一行分解为单词。我在您的代码中看到的唯一问题是您滥用了
stoi()
。它会在失败时引发异常,而您没有捕获该异常,例如:另一方面,如果您知道每行的第一个单词始终是非整数,则无条件忽略它,例如:
You already know how to read line-by-line, and break up a line into words based on commas. The only problem I see with your code is you are misusing
stoi()
. It throws an exception on failure, which you are not catching, eg:On the other hand, if you know the 1st word of each line is always a non-integer, then just ignore it unconditionally, eg: