C++ 如何将字符数组转换为int?
因此,输入文件如下所示:C++ 如何将字符数组转换为int?,c++,char,C++,Char,因此,输入文件如下所示: 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 char *ptr; for each line { ptr=strtok(lineOne," "); // do the initial strtok with a pointer to your string.
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
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
.....
}
}
}
尺寸=256
我使用getline
函数将第一行放入charlineOne[SIZE]
中,其他行放入lineTwo[SIZE]
和lineThree[SIZE]
中,但我需要能够修改每行中的最后5个数字,比如重新排序等等。我该怎么做呢?我不认为我可以将整个字符数组转换成整数,因为它的行中不仅有整数,而且我真的不知道该怎么做,我被卡住了
此外,我不能使用字符串库。首先,您将使用“标记化”输入行。这意味着它将把它分成块。当然,你会让它在空格处分开 只要数据遵循上面的模式,就可以跳过前两个,然后使用将ASCII转换为整数 将这些整数存储在一个数组中,您可以随意使用它们 一些用于获取所需值的粗略伪代码可能如下所示:
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
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
.....
}
}
}
正如另一个答案所建议的,我将使用
strok()
标记输入,但我也将实现一个简单的结构来保存每个记录。然后使用do-while循环读入每一行,将该行拆分为标记,并将其读入一条记录。名称后面是否总是有七个数字?是否总是有三行?哦。我读了“字符串库”,并想到C++字符串。你是说C字符串库是禁区吗?如果是这种情况,那么您应该在适当的位置使用fscanf()
和%d
。见@Code Guru不可能有whatever@kmort实际上我可以使用这个库,只是不知道如何“跳过”前两个?@MattRay通过显式测试index==0
和index==1
跳过循环中的前两个。不要对它们使用atoi()
,也不要将它们添加到存储阵列/struct/您选择的任何存储类型中。基本上,因为您知道数据的格式,所以在开始使用atoi()
之前,您可以计算令牌的数量以到达正确的位置。很抱歉,当我编写strtok函数时,如何跳过前两个?比如代码是什么样子的@kmort@MattRay没问题。我用一些粗略的伪代码更新了答案。你会有一些需要填写的内容,但这会给你一个想法。另外,我不确定是否要跳过前两个或前三个值。我写的伪代码只跳过了2,但是你可以很容易地让它跳过更多?lol抱歉,我是@kmortok的新手,所以根据我的输入文件,我会制作如下结构变量?名字、姓氏、id、num1、num2、num3、num4、num5?当然可以,或者只使用数字数组