【问题标题】:C++ program not inputting into a fileC ++程序未输入文件
【发布时间】:2019-02-11 01:16:30
【问题描述】:

这是我目前拥有的:

 #include <iostream>
 #include <fstream>
 #include <string>

using namespace std;

int main(){

fstream bookings("Schedule.txt");
fstream magicians("Magicians.txt");
fstream holidays("Holidays.txt");

//already tested to make sure these are open & they are

string test;
string holiday;

bookings >> test;

if(test.length()==0){
   while(getline(holidays, holiday)){
       bookings << holiday;
       cout << "test";

        }
    }

bookings.close();
magicians.close();
holidays.close();


  return 0;
}

我的Holidays.txt 包含以下内容:

Veteran's Day
Valentine's Day
Halloween
Christmas
New Years

我已确保我的文件位于正确的目录中并且文件实际上已打开。我逐步完成了程序以确保 holiday 得到相应的线路,但 bookings &lt;&lt; holiday; 似乎对我来说不能正常工作?

【问题讨论】:

  • 检查文件权限?你应该添加一个
  • 尝试同时读取和写入文件可能不是一个好主意。您只需要检查文件是否为空吗?在写入之前尝试关闭文件并重新打开它。
  • @FeiXiang 好像他正在尝试将假期文件附加到预订文件中
  • OP,您使用的是 Windows 吗?也许看看这个:stackoverflow.com/questions/17536570/…
  • 我正在使用 xcode。我以前也有&lt;&lt; endl;,但这没有用。该程序的最终目标是创建一个包含假期的时间表,然后在当天安排任何魔术师,因此我先导入假期然后我会检查他们是否安排在某一天,然后输入魔术师的名字相应地添加到日程文件中。

标签: c++ input fstream


【解决方案1】:

希望这会有所帮助。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

    fstream bookings("Schedule.txt", ofstream::app);
    fstream magicians("Magicians.txt");
    fstream holidays("Holidays.txt");

    string holiday;

    while(getline(holidays, holiday)){
       bookings << holiday << "\n";
       cout << holiday << "\n";

    }

    bookings.close();
    magicians.close();
    holidays.close();

  return 0;
}

【讨论】:

  • 完美运行,谢谢!介意解释一下 ofstream::app 到底在做什么吗?
  • 抱歉,基本上它会将文本附加到文件中(在末尾添加),而不是仅仅重写以前的内容,如果这有意义的话。如果不是 here 更多信息。
【解决方案2】:

您是否尝试过如下所示首先声明您的 ifstream 和 ofstream 变量?

ifstream inFile; ofstream outFile;

在将内容输入流之前,我使用以下方法打开输入文件。

inFile.open("input.txt"); outFile.open("toutput.txt");

我是 C++ 新手。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2016-01-24
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    相关资源
    最近更新 更多