我如何将一个char数组转换为int?

我如何将一个char数组转换为int?

问题描述:

因此,输入文件如下所示:

So the input file looks like this:

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 

SIZE = 256;

SIZE = 256;

我使用 getline 函数将第一行放入char lineOne [SIZE] 以及 lineTwo [SIZE] lineThree [SIZE] 但我需要能够修改每行中的最后5个数字,如重新排序他们等。我怎么会这样做?我不认为我可以将整个字符数组转换为一个int,因为它不仅有整数的行,我不知道该怎么做,我被困。

I used the getline function to put the first line into char lineOne[SIZE] and the others lines in lineTwo[SIZE] and lineThree[SIZE] but I need to be able to modify the last 5 numbers in each line, like reorder them and such. How would I go about doing this? I don't think I could convert the whole char array to an int because it has not only integers in the line and I don't really know what to do, I am stuck.

此外,我不能使用字符串库。

Also I can't use the string library.

首先, =http://www.cplusplus.com/reference/cstring/strtok/ =nofollow> strtok()来标记你的输入行。这意味着它会将其拆分成块。

First, you're going to use strtok() to "tokenize" your line of input. This means it will split it into chunks. You'll make it split at the spaces of course.

只要你的数据符合上面的模式,你可以跳过前两个,然后使用 atoi()将ASCII转换为整数。

As long as your data follows the pattern you have above, you can skip the first two, then use atoi() to convert from ASCII to integers.

将这些整数存储在数组中,你可以用他们喜欢的方式。

Store these integers in an array, and you can do what you like with them.

一些粗糙的伪代码, :

Some rough pseudocode for getting the values you want could look like this:

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
              .....
              }    
       }
    }