【问题标题】:C++ When saving data into another file, only the last line is written into new file, when instead I need the whole data to be writtenC ++将数据保存到另一个文件时,只有最后一行写入新文件,而我需要写入整个数据
【发布时间】: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


【解决方案1】:

您每次都在while 循环中打开文件。循环前打开文件,循环后关闭。

#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;
        ofstream outfile(nname);
        while (getline(myFile, text)) //reads the string line from text
        {
            cout << text << endl;
            outfile << text << endl;
        }
        outfile.close();
    }
    
    return 0;
}

【讨论】:

  • 该死的,谢谢你告诉我!在过去的几个小时里我一直被困在这个问题上哈哈哈
  • 如果我的回答有用,请考虑点赞 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 2022-01-26
  • 2015-11-25
相关资源
最近更新 更多