让我们看一下代码:
#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)
第二次的每次迭代中从那里开始的函数......
不幸的是,它没有第二次读取文件..