首页 > 解决方案 > 用不同的列读取每一行的全部内容

问题描述

我有一个这样的文本文件:

1 2 3
4
5 6 7 8
just with money we can live
2 5

用这段代码,我可以在屏幕上显示整个,但我不能把它放在一个字符串中,它的编译会出错:

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
   while(getline(cin, line2)) {
       cout << line2 << endl;
       line2 >> test;
} 

1-是否可以将整个文本文件放在“测试”中?
2-而不是使用这样的东西:

string test =
"1 2 3"
"4"
"5 6 7 8"
"just with money we can live"
"2 5";

是否可以使用循环和 freopen 或类似的东西?

我读了这个“在 C++ 中使用 ifstream 逐行读取文件”,但它是针对相同数量的列。

如果有网站可以回答我的问题,请给我。

标签: c++freopen

解决方案


让我们看一下这个片段:

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
while(getline(cin, line2)) {
       cout << line2 << endl;
}

这里发生的情况是,您文本文件(不是完全准确的术语)重定向到标准输入流(由cin此处的对象表示),然后逐行阅读。然后,在读取每一行之后,使用该cout对象将其打印到标准输出流。

要将文件读入字符串,您需要执行以下操作:

string test ="";
string line2;

freopen("a.txt", "rb", stdin);
while(getline(cin, line2)) {
       test += line2 + "\n";
}

在这里,您只需将行添加到test. 请注意,您还需要添加换行符,因为getline会删除它们。


推荐阅读