Home > Net >  How to convert character string to int in c
How to convert character string to int in c

Time:06-27

THis question is to convert character string to int.

if you input the character string, the input is converted to int.

for example, if you input the character string by keyboard "C35#37"

this program should add 3 5 3 7 and so result is 18.

so i get length of character string by strlen. and use "for statement" to distinguish if this input is char or int.(because if char is inputed in the atoi, the result is 0)

but this program i make run not well.

i want to know why this program is not working and how to this problem is solved.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
    char str[200];

    int len, i,sum=0;

    fputs("문자열을 입력해 주세요: ",stdout);
    fgets(str,sizeof(str),stdin);

    len = strlen(str);
    for(i=0; i<len; i  )
    {
      sum= sum   atoi(&str[i]);
    }
    printf("%d",sum);

    return 0;

}

result1:

> Executing task: ./blog <

문자열을 입력해 주세요: a12
14
Terminal will be reused by tasks, press any key to close it.

result2:

> Executing task: ./blog <

문자열을 입력해 주세요: 123   
149
Terminal will be reused by tasks, press any key to close it.

CodePudding user response:

There is no need to use the function atoi. Instead of this code snippet

len = strlen(str);
for(i=0; i<len; i  )
{
  sum= sum   atoi(&str[i]);
}

you could write

for ( const char *p = str; *p;   p )
{
    if ( '0' < *p && *p <= '9' ) sum  = *p - '0';
}

If to use your approach with the function atoi then for example the string 123 is parsed as 123 23 3 = 149.

  • Related