如何将 char 数组转换为 int? [关闭]

2024-01-12

所以输入文件如下所示:

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] and lineThree[SIZE]但我需要能够修改每行中的最后 5 个数字,例如重新排序等。我该怎么做呢?我不认为我可以将整个 char 数组转换为 int,因为它在行中不仅有整数,而且我真的不知道该怎么做,我被困住了。

我也无法使用字符串库。


首先,您将使用strtok() http://www.cplusplus.com/reference/cstring/strtok/“标记”您的输入行。这意味着它将把它分成块。当然,你要把它分成空格。

只要您的数据遵循上面的模式,您就可以跳过前两个,然后使用atoi() http://www.cplusplus.com/reference/cstdlib/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
              .....
              }    
       }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 char 数组转换为 int? [关闭] 的相关文章

随机推荐