【问题标题】:Problem while using input outout from files c++使用文件c ++的输入输出时出现问题
【发布时间】:2019-02-27 21:15:24
【问题描述】:

实现此代码时

当黑屏弹出时程序运行它没有其他东西等待了一段时间没有发生任何事情没有完成没有给我进程返回0知道它已经完成如果有人可以告诉我输出文件是空的这里有什么问题

#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

int main()
{
ifstream file;
ofstream out;

file.open("coinsCoint.txt");
out.open("1234567.txt");

int pennis,nickle,dime,quarter,sum=0;
float total;

while(!file.eof())
{
    file >> pennis >> nickle >> dime >> quarter;

    sum+=pennis+nickle*5+dime*10+quarter*25;

    total=sum/100.0;

}

out << "Total amount collected is: $" << fixed << showpoint << 
setprecision(2) << total;

file.close();
out.close();

return 0;

}

【问题讨论】:

  • 你甚至不测试你的文件是否可以成功打开。
  • 没有检查就做了很多代码你能告诉我如何回复你吗谢谢
  • while(!file.eof()) 是一个非常常见的错误。 Explanation here。一方面,它仅检查是否已到达文件末尾。如果出现其他任何问题,程序就会错过它。如果我没记错的话,这包括文件未打开。
  • 如果程序只是坐在那里什么都不做,请在循环中放置一个打印语句或使用调试器来单步执行代码。你可能会学到一些东西。

标签: c++ fileinputstream


【解决方案1】:
#include<iostream>
#include<fstream>
#include<iomanip>

using namespace std;

int main()
{
    ifstream file;
    ofstream out;

    file.open("coinsCoint.txt");

    int pennis = 0, nickle = 0, dime = 0, quarter = 0, sum = 0;
    float total = 0.0;

    /* check if file is opened */
    if (file.is_open()){

        while (!file.eof())
        {
            file >> pennis >> nickle >> dime >> quarter;
            cout << "pennis " << pennis << endl;
            cout << "nickle " << nickle << endl;
            cout << "dime " << dime << endl;
            cout << "quarter " << quarter << endl;

            sum += pennis + nickle * 5 + dime * 10 + quarter * 25;
            total = sum / 100.0;
            cout << "total " << total;
        }
        file.close();
    }
    /* return if error in file open */
    else {
        cout<< "can not open given file";
        return 0;
    }
    out.open("1234567.txt");

    if (out.is_open()){
        out << "Total amount collected is: $" << fixed << showpoint <<
            setprecision(2) << total;
        out.close();
    }
    return 0;
}

类似教程https://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/io/readtextfile.html

你应该经常检查文件是否被is_open()正确打开

您需要使用cout &lt;&lt; 打印来控制“黑屏”

文件看起来像

1
2
3
4

输出应该是这样的

pennis 1
nickle 2
dime 3
quarter 4
total 1.41Press <RETURN> to close this window...

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2016-08-22
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多