让我们来看看代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
string usrFileStr,
fileStr = "airNames.txt", // declaring string literal
sLine; // declaring a string obj
fstream inFile; // declaring a fstream obj
char ch;
cout << "Enter a file: ";
cin >> usrFileStr;
inFile.open( usrFileStr.c_str(), ios::in );
// at this point the file is open and we may parse the contents of it
while ( !inFile.eof() )
{
getline ( inFile, sLine ); // store contents of txt file into str Obj
for ( int x = 0; x < sLine.length(); x++ )
{
if ( sLine[ x ] == ',' )break; // when we hit a comma stop reading
//cout << sLine[ x ];
}
cout << endl;
}
while ( !inFile.eof() ) //read the file again until we reach end of file
{
// we will always want to start at this current postion;
inFile.seekp( 6L, ios::cur );
getline( inFile, sLine ); // overwrite the contents of sLine
for ( int y = 0; y < sLine.length(); y++ )
{
if ( sLine[ y ] == ',' )break; // hit a comma then goto seekp until eof
cout << sLine[ y ];
}
cout << endl;
}
inFile.clear();
inFile.close();
fgetc( stdin );
return 0;
}
我的文本文件格式与此类似:
string, string andthenspace, numbers, morenumbers
看起来我不能两次读取文件。每次都要检查EOF .. 第一个while条件有效,它给了我需要的东西,逗号前的第一个字段,不包括逗号。
所以我第二次想到,确定只需要在第二次迭代时启动的seekp(X,ios :: cur)函数。
不幸的是,它不是第二次读取文件..
答案 0 :(得分:3)
第一次读取EOF后,您可能需要清除流上的错误位。 也就是说,以及进行搜寻操作。
答案 1 :(得分:3)
首先,永远不要在你的while循环中测试eof,标志将是在之后你到达文件的末尾,即为时已晚,测试必须在读取之后完成,之前使用你期望阅读的内容。 - &GT;
while (std::getline(......))
然后,Jonathan Leffler给了你the solution,在调用seekg之前清除状态位。但是,您的方法似乎有点复杂Jamie pointed out。
答案 2 :(得分:1)
你似乎对此采取了错误的方式:
FILE * file;
file = fopen ("file.txt","r");
if (file!=NULL){
while (!feof(file)) {
fscanf(file,"%s ,%s ,%s ,%s",str1,str2,str3,str4);
}
fclose (file);
};
你可以显然扩展上面的例子,我没有时间检查它应该有效。