所以输入文件看起来是这样的:
Adam Zeller 45231 78 86 91 64 90 76
Barbara Young 274253 88 77 91 66 82 93
Carl Wilson 11223 87 77 76 78 77 82
大小 = 256;
我使用 getline
函数将第一行放入 char lineOne[SIZE]
并将其他行放入 lineTwo[SIZE]
和lineThree[SIZE]
但我需要能够修改每行中的最后 5 个数字,例如重新排序等。我该怎么做呢?我不认为我可以将整个 char 数组转换为 int,因为它不仅在行中有整数而且我真的不知道该怎么做,我被卡住了。
我也不能使用字符串库。
首先,您将使用 strtok() “标记化”您的输入行。这意味着它将把它分成 block 。当然,您会在空格处将其拆分。
只要您的数据遵循上述模式,您就可以跳过前两个,然后使用 atoi()从 ASCII 转换为整数。
将这些整数存储在一个数组中,你可以用它们做任何你喜欢的事情。
获取所需值的粗略伪代码如下所示:
char *ptr;
for each line
{
ptr=strtok(lineOne," "); // do the initial strtok with a pointer to your string.
//At this point ptr points to the first name
for(number of things in the line using an index variable)
{
ptr=strtok(NULL," "); // at this point ptr points to the last name
if(index==0)
{
continue; //causes the for loop to skip the rest and go to the next iteration
}
else
{
ptr=strtok(NULL," "); // at this point ptr points to one of the integer values,
//index=1 being the first one.... (careful not to get off by one here)
int value=atoi(ptr)
/// stuff the value into your array... etc...
storageArray[index-1]=value; /// or something like this
.....
}
}
}