c++ - 从 .txt 文件 C++ 中获取多于一行
问题描述
我想从 data.txt 文件中提取不止一行。我只能拿第一个。我尝试使用 while 循环,但在这种情况下我似乎不知道如何使用它。
用while循环编辑:
#include <iostream>
#include <fstream>
using namespace std;
int zapis()
{
fstream file;
string text;
file.open("data.txt", ios::app);
cout << "Type in text that you would like to store: ";
getline(cin, text);
file << text << endl;
file.close();
return 0;
}
int odczyt()
{
fstream file;
string line;
int nr_lini = 1;
file.open("data.txt", ios::in);
if(file.good()==false)
{
cout << "Error occured!";
}
else
{
while(getline(file, line))
{
getline(file, line);
cout << line;
}
}
file.close();
return 0;
}
int main()
{
zapis();
odczyt();
return 0;
}
解决方案
为什么在你的循环中调用 getline两次?还要注意分号
while(getline(file, line));
^
你认为那里的分号有什么作用?
这是对的
while (getline(file, line))
{
cout << line;
}
推荐阅读
- javascript - 为什么在安卓浏览器上无法播放音频?
- ios - 如何在 SwiftUI 中使用 UIAccessibility.post(notification: .layoutChanged, argument: nil) 将焦点移动到特定视图
- java - Java 排序列表的最佳方式,而不是使用多个循环
- amazon-web-services - 有没有办法从 CFT 中的 DNS 名称中获取 HostedZoneId?
- stm32 - ST-LINK/V2 中的 RX 和 TX 有什么用
- php - 无法使用 laravel websockets 获取数据库表更改的实时更新
- javascript - 收到此错误:无法读取未定义的属性“长度”
- amazon-web-services - AWS S3.getSignedUrl() :到期语义
- python - Django 迁移——如何在迁移过程中擦除模型?
- angular - 在 Angular 中转换更新 CRUD 表单日期