You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++作业库存显示异常:CMD输出随机数,需实现指定格式

C++库存显示功能输出随机数的问题排查

问题描述

我正在完成一项C++课程作业,执行库存显示功能时CMD窗口输出大量随机数。期望的库存输出格式示例:

shea butter 2.00 20 0
mint shampoo 5.00 15 1

以下是我的代码实现:

//Void from Assignment given
void logo();
void menu();
void writeFile(string itemNames[], double itemCost[], int itemNoShip[][2]);
void displayInventory(string itemNames[], double itemCost[], int itemNoShip[][2]);
bool readInventory(string itemNames[], double itemCost[], int itemNoShip[][2]);

const int MAX = 10;

const string FILE_INPUT = "inputInventory.txt";
const string FILE_OUTPUT = "outputInventory.txt";


int main()
{
    const int MAX = 10;
    string itemNames[MAX];
    double itemCost[MAX];
    int itemNoShip[MAX][2];
    int choice;
    ifstream inputFile(FILE_INPUT, ios::in);
    string line;

    for (int i = 0; i < MAX; i++)
    {
        inputFile >> itemNames[i] >> itemCost[i] >> itemNoShip[i][0] >> itemNoShip[i][1];
    }

    do
    {
        logo();
        menu();
        cin >> choice;
        switch (choice)
        {

        case 1:
            if (readInventory(itemNames, itemCost, itemNoShip))
            {
                cout << "File read succesfully...\n";
            }
            break;
            return 0;

        case 2:
        {
            displayInventory(itemNames, itemCost, itemNoShip);
            cout << "Inventory not yet read from file. Please choose option 1 first." << endl;
        }
        break;

        case 3:
        {
            cout << "File written to outputInventory.txt..." << endl;
            cout << endl;
            writeFile(itemNames, itemCost, itemNoShip); //testing switch statement 3
            break;
        }
        case 4:
            cout << "Invalid Menu Item entered...must enter 1-4..."; //testing switch statement 4
            cout << "Exiting program..." << endl;
            break;

        default:

            break;
        }
    } while (choice != 4);

    return 0;

    inputFile.close();

}
//Missael Ramirez
void logo() {
    cout << "*****************************************\n";
    cout << "           Vander Vormar's Galaxy Diner\n";
    cout << "*****************************************\n";
    cout << "         **         **\n";
    cout << "         **         **\n";
    cout << "         **         **\n";
    cout << "         **         **\n";
    cout << "         **         **\n";
    cout << "          ***********\n";
    cout << "           *********\n";
    cout << "             *****\n";
    cout << "               **\n";
    cout << "*****************************************\n";
}

void menu()
{
    cout << "1.  Read Inventory" << endl;
    cout << "2.  Display Inventory" << endl;
    cout << "3.  Write to file" << endl;
    cout << "4.  Exit" << endl;
}


void writeFile(string itemNames[], double itemCost[], int itemNoShip[MAX][2])
{
    ofstream outputFile;
    outputFile.open(FILE_OUTPUT, ios::out);
    for (int i = 0; i < MAX; i++)
    {
        outputFile << setw(13) << itemNames[i] << setw(6) << itemCost[i] << setw(6);
        outputFile << itemNoShip[i][0] << setw(6) << itemNoShip[i][1] << endl;
    }


}

void displayInventory(string itemNames[], double itemCost[], int itemNoShip[][2])
{
    cout << "Item Name\tCost\tNo.Stock\tShipping (1-Yes 0-No)\n";

    for (int i = 0; i < MAX; i++) {
        cout << itemNames[i] << "\t" << itemCost[i] << "\t" << itemNoShip[i][0] << "\t" << itemNoShip[i][1];
    }


}

bool readInventory(string itemNames[], double itemCost[], int itemNoShip[][2]) {
    ifstream inputFile;

    inputFile.open("inputInventory.txt");

    if (inputFile.fail()) {
        inputFile.close();
        return false;
    }
    for (int i = 0; i < MAX; i++) {
        getline(inputFile, itemNames[i]);
        inputFile >> itemCost[i];
        inputFile >> itemNoShip[i][0] >> itemNoShip[i][1];
    }

    inputFile.close();
    return true;
    {
        cout << "File missing!" << endl;



        return true;
    }
}

    inputFile.close();
    return true;
    {
        cout << "File missing!" << endl;



        return true;
    }
}

代码中的关键错误及修复方案

1. main函数提前读取文件且未处理打开失败

main函数开头直接执行文件读取循环,但未检查文件是否成功打开。若文件不存在/打开失败,会读取垃圾值(随机数),导致后续显示异常。此外这段逻辑完全多余,文件读取应交给readInventory函数处理。
修复:删除main函数中ifstream inputFile(FILE_INPUT, ios::in);到for循环的所有代码。

2. readInventory函数读取逻辑错误

  • 用getline读取商品名后,直接用>>读取数值会残留换行符,导致读取错位;
  • 商品名包含空格(如shea butter),>>只能读取空格前的部分,无法完整获取商品名;
  • 函数末尾存在无法执行的冗余代码块,会导致编译错误。

修复示例(适配带空格的商品名格式):

#include <sstream>
#include <vector>

bool readInventory(string itemNames[], double itemCost[], int itemNoShip[][2]) {
    ifstream inputFile("inputInventory.txt");
    if (!inputFile.is_open()) {
        cout << "File missing!" << endl;
        return false;
    }

    string line;
    int i = 0;
    while (getline(inputFile, line) && i < MAX) {
        istringstream iss(line);
        vector<string> parts;
        string part;
        // 将整行拆分为多个片段
        while (iss >> part) {
            parts.push_back(part);
        }
        if (parts.size() >= 3) {
            // 拼接商品名(除最后三个数值片段)
            itemNames[i] = "";
            for (int j = 0; j < parts.size() - 3; j++) {
                if (j > 0) itemNames[i] += " ";
                itemNames[i] += parts[j];
            }
            // 读取数值
            itemCost[i] = stod(parts[parts.size()-3]);
            itemNoShip[i][0] = stoi(parts[parts.size()-2]);
            itemNoShip[i][1] = stoi(parts[parts.size()-1]);
            i++;
        }
    }

    inputFile.close();
    return true;
}

3. displayInventory函数格式问题

  • 循环输出时无换行,所有内容挤在一起;
  • 价格未格式化,无法输出2.00这类两位小数格式;
  • 未跳过空商品项(若文件商品数量少于MAX)。

修复:

#include <iomanip>

void displayInventory(string itemNames[], double itemCost[], int itemNoShip[][2]) {
    cout << "Item Name\tCost\tNo.Stock\tShipping (1-Yes 0-No)\n";
    cout << fixed << setprecision(2); // 固定两位小数
    for (int i = 0; i < MAX; i++) {
        if (itemNames[i].empty()) break; // 跳过空项
        cout << itemNames[i] << "\t" << itemCost[i] << "\t" 
             << itemNoShip[i][0] << "\t\t" << itemNoShip[i][1] << endl;
    }
}

4. main函数switch逻辑错误

  • case 1中存在多余的return 0;,导致读取文件后程序直接退出;
  • case 2无论是否读取文件,都会输出未读取提示,逻辑矛盾。

修复:
在main函数中添加标记变量bool inventoryLoaded = false;,修改switch分支:

case 1:
    if (readInventory(itemNames, itemCost, itemNoShip)) {
        cout << "File read succesfully...\n";
        inventoryLoaded = true;
    } else {
        cout << "Failed to read inventory file!\n";
    }
    break; // 删除原有的return 0;

case 2:
    if (!inventoryLoaded) {
        cout << "Inventory not yet read from file. Please choose option 1 first." << endl;
    } else {
        displayInventory(itemNames, itemCost, itemNoShip);
    }
    break;

5. 缺失必要头文件

代码使用了ifstream、istringstream、setprecision等工具,需补充头文件:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
using namespace std; // 或逐个使用std::前缀

6. 全局与局部MAX冲突

全局已定义const int MAX = 10;,main函数中重复定义会导致冲突,删除main中的const int MAX = 10;。

额外注意事项

确保inputInventory.txt文件格式正确,每行对应一个商品,示例:

shea butter 2.00 20 0
mint shampoo 5.00 15 1

内容的提问来源于stack exchange,提问作者NekoPria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 10:43:10