【发布时间】: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
*/
}
【问题讨论】:
-
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 个有效索引:0、1、2、3和4。评估foo[5]会在数组末尾读取一个int,这将是内存中发生的任何数据。更糟糕的是,分配到foo[5] = 12会覆盖该内存,这可能是另一个变量的一部分。 -
嘿。你修复你的代码。我认为您的数组声明应该是
int a[num][3];,但我只花了一点时间看。 -
唉...请不要发文字图片,只发文字。