c++ - 用不同的列读取每一行的全部内容
问题描述
我有一个这样的文本文件:
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 逐行读取文件”,但它是针对相同数量的列。
如果有网站可以回答我的问题,请给我。
解决方案
让我们看一下这个片段:
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
会删除它们。
推荐阅读
- java - 使用 BouncyCastle 生成 PBE-MD5-DES 加密密钥以与 OpenSSL pkcs8 兼容
- java - 在 android、firebase 中获取聊天应用程序的正确时间戳
- string - 从 PDF 中提取特定的文本字符串
- node.js - docker compose环境变量在nodejs容器中未定义
- linux - 替换 Shell 脚本中特定范围的 xml 属性值
- c++ - 我把一个shared_ptr放到了map中,但是为什么程序结束前对象就被破坏了呢?
- laravel - Laravel-Excel 从 v2 升级到 v3。缺少 NewExcelFile 的问题
- javascript - 如何在 Javascript 中合并对象?
- java - 如何修复有关在 Java 中格式化日期的错误?
- asp.net - 下拉列表数据库