如何用c++将txt文本中一行一行的读入string里。

假如我的txt文本如下
>01
1234
4567
8910

我想把它读入内存存成
string str = “12345678910”
这样可以么?
或者是
str[0]=>01
str[1]=1234
str[2]=4567
str[3]=8910
...
我自己写的代码发现显示的是空的,求大神指点。

ifstream fin;
cout<<" Enter the reference file: \n";
string inname;
getline(cin,inname,'\n');

string temp[20];
while(fin.good())
{
getline(fin,temp[i]);
cout<<temp[i]<<endl;
i++;
}

ps,并不是只想读取文件里面的东西,是想对文件里面第行以后的东西做一些简单的处理,比如输出的时候变成:
>01
123 5 4
45 7
8910
所以需要整合文件里的字符串。

请大神写的详细一点,谢过~~

假设你的txt文本名为test.txt
代码如下:

string temp;//temp用来将所有的内容存入,用来存储“12345678910”的
ifstream test("test.txt", ios::in);
string str;
while (getline(test, str))//按行读文件
{
cout << str << endl;//这里可以不要,只是用来看你自己txt文档中原来的内容
if (str[0] == '>')
continue;
else
temp.insert(temp.length(),str,0,str.size());//最终都存入temp中
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-06
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main() {
ifstream fin;
string temp[20],total = "";
char filename[60];
int i = 0;
cout << " Enter the reference file: \n";
cin.getline(filename,'\n');
fin.open(filename,ios::in);
while(fin.good() && i < 20){
getline(fin,temp[i]);
total += temp[i]; // += 已被重载
cout << temp[i] << endl;
i++;
}
//
return 0;
}

本回答被提问者和网友采纳
相似回答