【发布时间】:2021-12-20 01:52:01
【问题描述】:
考虑以下几点:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cctype>
#include <array>
using namespace std;
int main(){
string nname;
cout << "Enter new name for file" << endl; // prompts user to enter new filename
cin >> nname;
fstream myFile;
myFile.open("example.txt", ios::in); //opens the data folder loaded
if (myFile.is_open()){
cout << "Is open now" << endl << endl;
string text;
while(getline(myFile, text,'\n')) //reads the string line from text
{
cout << text << endl;
ofstream outfile(nname);
outfile << text;
outfile.close();
}
}
return 0;
}
“example.txt”是:
5
Id,Age,math,science,malay
2
1201101128,20,30,12,30
1201101127,33,44,66,11
新文件只有“1201101127,33,44,66,11”行,不包含其他行。 我读过“while”循环正在制作它,以便它一个接一个地读取所有行,但只输出最后一个。我的问题是,你如何让它输出所有的行?
【问题讨论】:
-
为什么在
getline中给定界符\n? -
您正在打开并因此循环截断文件。
-
我实际上是从一个网站获取代码,不记得是哪一个。默认情况下它有 \n 所以我没有改变它。如果我一开始就没有它会更好吗?
标签: c++ string while-loop io output