如何用c++将文本所有内容全部读入呢?可以使用getline函数,进行逐行读入。直接上程序:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char *filePath = "E:\\test.txt";
ifstream file;
file.open(filePath, ios::in);
if (!file.is_open())
return 0;
string strLine;
string s;
//file >> s;
while (getline(file, strLine))
{
if (strLine.empty())
continue;
cout << strLine << endl;
s = s + strLine+"\n";
}
int index=s.find("prawn");
cout << index << " " << s.substr(index, s.size()) << endl;
return 0;
}
其中s将文本中所有内容保存了,包括回车和空格。