Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert character string to int in c

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading