例: 丽丽 战三 王五
小明 空三
第一次一次性读出(丽丽 战三 王五),依次读( 小明 空三)。
不要网上的答案,因为网上的有错,求大侠指教。
//在工程下面建立一个文件 xiaojiba.txt
#include <iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
cout<<"input the filename:"<<endl;
string filename;
cin>>filename;
ifstream infile(filename.c_str());
string temp;
while(getline(infile,temp))
{
cout<<temp<<endl;
}
cout << "Hello world!" << endl;
return 0;
}
重定向输入流命令行: prog <prog.c
可以使用C++的库函数getline实现。
getline会生成一个包含一串从输入流读入的字符的字符串,直到以下情况发生会导致生成的此字符串结束。
1)读到文件结束符;
2)遇到函数指定的结束符;
3)输入达到最大限度。
getline有两种重载:
istream &getline( char *buffer, streamsize num );
istream &getline( char *buffer, streamsize num, char delim );
参数说明:
buffer: 读取的数据将存在buffer中。
num:最多读取num个字符。即之前所说的最大限度。
delim:结束符,当遇到指定的结束符时将结束输入。在第一种重载中,结束符为\n,即遇到换行结束。
所以要实现整行读取,使用第一种重载就可以了。示例代码如下:
#include <iostream>