我正在尝试编写一个程序,该程序接收来自用户的输入并使用提供的输入创建一个二维数组。它将值正确保存到数组中,但程序无法正确执行保存。
它可以保存错误的值。这是代码:
#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
*/
}
答案 0 :(得分:1)
所以,而不是用
声明int a[num-1][2];
我应该用
int a[num][3]
因为我需要3列和num行数。使用早期的代码,我尝试读取数组外的值。现在,代码不会在数组外读取。