c++ - 我如何将 char 数组转换为 int?

标签 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 

大小 = 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
              .....
              }    
       }
    }

关于c++ - 我如何将 char 数组转换为 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447770/

相关文章:

c++ - 将 char 数组的最后 8 个字节设置为 __uint64

c++ - 在 C++ 中从 Tensorflow 的 .meta 文件加载图形以进行推理

c - Scanf 不起作用

c++ - 连接 const char * 字符串

java - java的chars()流如何与reduce一起工作?它使用字符编码吗?

const char* 仍然修改指向的值

c++ - 在这种情况下,qobject_cast 不应该默默地失败吗?

C++ 如何向字段添加额外信息

c++ - 为什么 g++ 在 Ubuntu 上不支持带有分配器构造函数的函数?

字符数组不会编译