【发布时间】:2016-02-20 20:30:20
【问题描述】:
我正在为我的编程项目创建一个零用现金系统程序,它涉及我使用指针数组来模拟表格。
我已经创建了一个部分,要求用户输入附加数据以附加到我当前的表中,但是当我的可执行文件到达要求用户输入的部分时,我的可执行文件崩溃(在我的情况下,它将是getline(cin,my2dArrayPointerHere[][]) )
谁能指出我做错了什么?我也尝试使用常规的非指针字符串数组,但我仍然遇到同样的崩溃。
顺便说一句,我正在使用 std 命名空间。也请忽略一些cmets。这些是为我的队友准备的,他们可能对我的代码有疑问。
int numTrans;
char tempChar[1000];
double tempHolder;
string **tempDataHolder;
cout<<"Input number of transactions to add: ";
cin>>numTrans;
tempDataHolder = new string*[numTrans]; //pointer array
for(i=0;i<numTrans;i++)
tempDataHolder[i] = new string[col];
cout<<"\nPlease input the following data as necessary: \n";
for(ir=0; ir<numTrans;ir++)
{
cout<<"Date Requested: "; //This may seem unnecessary but some companies require paper
//documentation aside from a system to approve petty cash
//and sometimes the accounting staff has too much to do to
//perform data entry jobs in realtime such as this
getline(cin,tempDataHolder[ir][col]);
cout<<"Person Requesting Funds: ";
getline(cin,tempDataHolder[ir][col+1]);
cout<<"Person who approved request: ";
getline(cin,tempDataHolder[ir][col+2]);
cout<<"Amount Requested: Php. ";
cin>>tempHolder; //temp double number to properly format money
ostringstream convert;
convert<<tempHolder;
tempDataHolder[ir][col+3] = convert.str();
cout<<"Particulars: ";
getline(cin,tempDataHolder[ir][col+4]);
tempDataHolder[ir][col+5] = " "; //initialized to empty space because
tempDataHolder[ir][col+6] = " "; //data has not yet been retrieved
tempDataHolder[ir][col+7] = " "; //through liquidation
tempDataHolder[ir][col+8] = " ";
tempDataHolder[ir][col+9] = "false";
}
tableSize = deterSize(curFileName) + (numTrans*col); //this will ensure the next table will house all new elements as well
readCurFile(curFileName, tableSize);
displayCurTable(tableSize);
delete tempDataHolder;
【问题讨论】:
-
想知道如果老师真的教 C++,而不是 C 的课程,可以节省多少时间和头痛!
-
在第一个维度中,您在范围
[0,numTrans]中进行迭代,该范围与分配的大小一致。在第二个维度中,您在[col, col+9]范围内进行迭代,而您只分配了[0,col]。为什么会这样?可能是崩溃的原因。 -
天哪。我明白为什么......呃。在这里,我在想也许我在语法上做错了,但这是合乎逻辑的!我被教导要始终在索引中使用变量,但我忘记了我的列不需要索引。谢谢大家!
-
“我被教导要始终在索引中使用变量”——这听起来几乎是无稽之谈。使用程序逻辑告诉您用作数组索引的任何内容。在一定范围内使用常量索引是完全有效的。 (虽然当范围越来越大时,可能是时候将设计重新考虑为结构或类似的东西了。)
-
这就是计划,我已经可以做到了,但我更愿意等到我们接触到这个主题(我有 C++ 的先验知识,但我太生疏了,我认为等待教授的课程会有所帮助我更好)。
标签: c++ arrays pointers dynamic-memory-allocation