一个应该很简单的问题:逐行读去并操作
各位大虾,小弟初学C++,请问如何用C++语言对一个文本文件逐行读取?我现在用的是getline函数,但是,如何进行循环设置?如何终止?get(ch)=EOF 可以吗?就是读取一行并操作后,再跳到另一行,在对行进行操作,我需要将读取到的那一行记录到一个字符数组中,再进行操作(因为再操作过程中我需要嵌套使用switch语句),操作完成后对数组进行清空。
谢谢~~~!!
[解决办法]
ifstream infile( "file ",ios::binary);
string m_tempchannel;
while(infile> > m_tempchannel&&infile)
{
}
[解决办法]
统计文件的单词数
读文件的一行
int main()
{
ifstream infile;
string filename;
cout < < "Please enter the file name: ";
cin > > filename;
infile.open(filename.c_str());
string line;
getline(infile, line, '\n ');
infile.close();
vector <string> wordsOfLine;
string::size_type pos = 0, prev_pos =0;
string word;
while ((pos = line.find_first_of( ' ', pos)) != string::npos)
{
word = line.substr(prev_pos, pos - prev_pos);
prev_pos = ++pos;
wordsOfLine.push_back(word);
}
wordsOfLine.push_back(line.substr(prev_pos, pos - prev_pos));
size_t numOfLine = wordsOfLine.size();
cout < < numOfLine < < "words " < < endl;
}
读整个文件的:
int main()
{
ifstream infile;
string filename;
cout < < "Please enter the file name: ";
cin > > filename;
infile.open(filename.c_str());
string line;
vector <string> wordsOfFile;
while (getline(infile, line, '\n '))
{
string::size_type pos = 0, prev_pos =0;
string word;
while ((pos = line.find_first_of( ' ', pos)) != string::npos)
{
word = line.substr(prev_pos, pos - prev_pos);
prev_pos = ++pos;
wordsOfFile.push_back(word);
}
wordsOfFile.push_back(line.substr(prev_pos, pos - prev_pos));
}
infile.close();
size_t numOfLine = wordsOfFile.size();
cout < < numOfLine < < "words " < < endl;
return 0;
}