所以我有一个单行的文本文件,看起来像这样:
我试图做的是从文本文件中读取每个整数。我已经尝试过一些看起来像这样的代码[[史蒂夫3西尔维亚7克雷格14丽莎14布莱恩4夏洛特9乔丹6
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int a;
ifstream inStream;
inStream.open("file.txt");
// case for file open failing
if ( inStream.fail() )
{
cout << "File open failed.\n";
exit(1);
}
//attempting to read each integer and print it to see if it worked right
while( inStream.good() )
{
inStream>>a;
cout<<a;
}
return 0;
}
我知道当整个文件仅由整数组成,或者如果整个文件不是一行时,这很简单,但是在这种情况下我遇到了麻烦
名称号码名称号码 ...那么您可以执行以下操作:
int a;
string name;
// read name first then number
while( inStream >> name >> a )
{
cout << a << endl;
}
使用进行阅读时,您不能跳过名称,但可以阅读而对它们不做任何事情。>>