C++ 从文件中输入

标签 c++ input file-io

我必须编写一个关于女童子军 cookie 的程序,该程序输入一个 .txt 文件,其中包含客户的名字、购买的盒子数量和 cookie 的名称。盒子的价格是 3.50 美元。在程序中,我必须显示客户名称、售出的盒子、cookie 的名称和应付金额。最后,显示客户数量、已售出的总箱数和应付总金额。这是我到目前为止所拥有的,我不确定为什么它不运行,或者至少说找不到文件,我已经在我的项目文件夹中创建了 .txt 文件,感谢任何帮助,谢谢! 我得到的错误是“无法启动程序...系统找不到指定的文件”。我很确定我的文件在正确的位置

#include <iomanip>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    ifstream inFile;
    //Declare Variables

    string firstName;
    string cookieName;

    int boxesSold;
    int numCustomers;
    double amountDue;
    int totalCustomers;
    int totalBoxesSold = 0;
    double totalAmount = 0;

    inFile.open("girlscout.txt");
    if (inFile)
    {
        cout << "Customer     Boxes     Cookie Name" << endl;
        cout << "Name                              " << endl;

        while(!inFile.eof())//Not end of file
        {
            inFile >> firstName;
            inFile >> boxesSold;
            inFile >> cookieName;

            totalBoxesSold += boxesSold;
            totalAmount = boxesSold * 3.50;

            cout << setprecision(2) << fixed << showpoint;
            cout << setw(2) << firstName
            << right << setw(7) << boxesSold
            << cookieName << endl;
        }

        cout << "Total Boxes Sold: " << totalBoxesSold;
        cout << "Total Amount: " << totalAmount;
        inFile.close();
    }

    else
    {
        cout << "Could not open file " << endl;
    }

    system("pause");
    return 0;
}

最佳答案

我认为你的问题是文件 girlscout.txt 不在你需要它的目录中,以便你的程序找到它。您可以通过将完整路径放入您的 inFile.open 调用中来解决此问题,或者在同一目录中编译并运行带有您的 girlscout.txt 文件的可执行文件

关于C++ 从文件中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14943992/

相关文章:

Java访问大文件

java - 为什么从 cmd 调用 jar 时 java 扫描仪不起作用?

c++ - 在 C++ 中如何获取整数的第 j 个最高有效位?

c++ - 用于在两个函数之间进行选择的仿函数

python - 尝试使用正则表达式从脚本注释中提取日期和版本号

javascript - 达到 maxlength 后如何限制输入的字符?

C 编程 — 获取字符串中的多个单词

python - 解析apache日志文件

c++ - 为什么 C 编译器不能以直观的方式进行有符号/无符号比较

C++:IF 未在此范围内声明