【问题标题】:How do I write a 2-dimensional array to a text file?如何将二维数组写入文本文件?
【发布时间】:2017-11-28 08:17:15
【问题描述】:

我正在尝试编写一个程序,它接收来自用户的输入并使用提供的输入创建一个二维数组。它将值正确保存到数组中,但程序无法正确执行保存。

它保存了错误的值。代码如下:

#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;

int main()
{

 int num;
 int productId =1;


     cout << "Welcome To The Store Manager Registry! \n ";

     cout << "How Many Products Would You Like To Add To The Registry?\n";

     cin >> num;

 if (num <= 0)
        cout << "Please Enter A Valid Input More Than 0";

 int a[num-1][2]; //creates a two dimensional array for items
 for (;productId-1<num;productId++)
    {
         cout << "\nPlease Enter The Cost Price For Product Id "<< productId << " (ONLY NUMBERS) \n";
         cin >> a[productId-1][0];
         cout << "\nPlease Enter The Selling Price For Product Id "<< productId << " (ONLY NUMBERS) \n";
         cin >> a[productId-1][1];
         a[productId-1][2]=a[productId-1][1]-a[productId-1][0];
    } //Receives Input And Saves Values To Array
    cout << "Saving Data...";
    ofstream outputfile;
    outputfile.open("Statistics.txt");



 for (int b = 1;b<=num;b++){
        outputfile <<a[b-1][0]<<","<<a[b-1][1]<<","<<a[b-1][2]<<endl;//saves values to file
 }
        outputfile.close();


    /* Saves Array In This Format:
    Product Id       Cost Price          Selling price          Profit
    1                    10                   20                  10
    2                    20                   20                  0
    3                    30                   10                  -20

    But, Prints In This Format

        Product Id       Cost Price          Selling price          Profit
    1                    10                   20                     20
    2                    20                   20                     30
    3                    30                   10                    -20

    */


}

这是输入: 这是它保存到的 .txt 文件: 所以,最终,值不匹配,我被这个坏掉的程序卡住了。

【问题讨论】:

  • int a[num-1][2]; 甚至不是有效的c++。即使是。错了。
  • 挑选您的英语:您不必将每个单词都大写。看起来您需要a[3][4],因为您有 3 行和 4 列。如果你的编译器支持变量数组,你可以声明a[num][4]。数组索引从零开始直到num,例如a[0][0] -> array[num-1][0]。如果你是初学者,也许你应该从一维数组开始。
  • 同意@BarmakShemirani。数组 int foo[5]; 有 5 个有效索引:01234。评估foo[5] 会在数组末尾读取一个int,这将是内存中发生的任何数据。更糟糕的是,分配foo[5] = 12 会覆盖该内存,这可能是另一个变量的一部分。
  • 嘿。你修复你的代码。我认为您的数组声明应该是int a[num][3];,但我只花了一点时间看。
  • 唉...请不要发文字图片,只发文​​字。

标签: c++ arrays file fstream


【解决方案1】:

所以,不要用

声明
int a[num-1][2];

我应该用过

int a[num][3]

因为我需要 3 列和 num 行。使用较早的代码,我尝试读取数组外的值。现在,代码不会在数组之外读取。

【讨论】:

    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 2021-12-19
    • 2018-03-08
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多