当我在cstring中解析信息时,我无法正确地获取算法。
我有一个与此类似的数据文件。
Hammer 1 1.00
Drill 2 2.00
Saw 3 3.00
Level 4 4.00
Pick 5 5.00
Nail 6 6.00
Mallet 7 7.00
Putty 8 8.00
Stapler 9 9.00
Desk 10 10.00
Table 11 11.00
Marker 12 12.00
数据文件可以有空格来开始每一行或每个值之间。 该数据文件的格式为名称,数量和价格。在正确解析时,每个名称,数量和价格都存储在结构数组中。
我需要在这个问题上使用cstrings,因为我现在正在从一本书中学习它们。
到目前为止,这是我的算法,我认为我的程序刚挂起的某个地方陷入了一段时间。
对于我的代码,我的想法是。虽然来自数据文件的行的readLineIndex
处的值不是空字符,但请执行内部操作。如果cstring在cstring中的任何地方都有一个空行,请向我的readLineIndex
添加一个空格行,如果该字符是字母数字,则将其复制到临时数组中并移动到下一个字符并重复上述操作直到获得空格。一旦程序命中空白存储,该值就会进入正确的结构变量数组。程序会通过计数知道它的值是什么,因为我从输入文件中只得到3个变量我只是说如果我在计数器上检索的第一个变量是1然后将它存储到数组[structureCounter] .product ,如果它是2将它存储到数组[structureCounter] .quantity,如果它是3存储到数组[structureCounter] .unitPrice。每次解析完成并且文件的读取不在行尾时,structureCounter也只上升一个。
这就是我的函数被调用的方式。 MAX_INVENTORY = 12。
while(!inFile.getline(readLine, MAX_CHARACTERS, '\n').eof() && structureCounter < MAX_INVENTORY)
{
parseInformation(readLine,inventory, readLineIndex, structureCounter);
structureCounter += 1;
}
函数算法。
void parseInformation(OneLine readLine,OneItem inventory[], int & readLineIndex, int & structureCounter)
{
int tempIndex = 0;
int valueCounter = 0;
OneLine tempArray;
while(readLine[readLineIndex] != '\0')
{
while(readLine[readLineIndex] == ' ')
{
readLineIndex += 1;
}
while(isalnum(readLine[readLineIndex]))
{
tempArray[tempIndex] = readLine[readLineIndex];
tempIndex += 1;
readLineIndex += 1;
}
if(valueCounter == 0)
{
strcpy(inventory[structureCounter].product,tempArray);
valueCounter += 1;
}
if(valueCounter == 1)
{
inventory[structureCounter].quantity = atoi(tempArray);
valueCounter += 1;
}
if (valueCounter == 2)
{
inventory[structureCounter].unitPrice = atof(tempArray);
}
}
return;
答案 0 :(得分:0)
首先,在致电tempArray
之前,您没有向strcpy
添加空终止符。其次,在您复制tempArray
后,您需要将tempIndex
重置为0
,以便将其用于下一个字段。第三,从tempArray
复制到product
后,您将valueCounter
从0
增加到1
。因此,下一个测试if (valueCounter == 1)
将成功,它会尝试将已解析的tempArray
放入quantity
;然后你将它增加到2
,下一个测试将成功,你将尝试将它放入unitPrice
。您应该使用else if
或switch
语句,这样您才能执行其中一项;您还可以在之后增加valueCounter
,即可完成所有测试。
void parseInformation(OneLine readLine,OneItem inventory[], int & readLineIndex, int & structureCounter) {
int tempIndex = 0;
int valueCounter = 0;
OneLine tempArray;
while(readLine[readLineIndex] != '\0') {
while(readLine[readLineIndex] == ' ') {
readLineIndex += 1;
}
while(isalnum(readLine[readLineIndex])) {
tempArray[tempIndex] = readLine[readLineIndex];
tempIndex += 1;
readLineIndex += 1;
}
tempArray[tempIndex] = 0; // Add null terminator
switch (valueCounter) {
case 0:
strcpy(inventory[structureCounter].product,tempArray);
break;
case 1:
inventory[structureCounter].quantity = atoi(tempArray);
break;
case 2:
inventory[structureCounter].unitPrice = atof(tempArray);
break;
}
valueCounter++;
}
return;
}