0

My problem statement was to accept a string of numbers and display the different numbers on screen. So i tried to use strtok() to divide the string to different numbers and atoi() to convert these to numbers. But I'm getting runtime error.. I have also attached a sample code.

Input

1 22 123 89 12 as a string

Output

1 22 123 89 12 as numbers

I need to do mathematical operations on these numbers. So I must convert from integer to string.

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

int main ()
{
    int i,j;
    char buffer [256];

    char *token;
    const char s[2]= " ";
    fgets (buffer, 256, stdin);

    token=strtok(buffer,s);
    i = atoi (token);
    printf("%d \n",i);
    while (token!=NULL)
                {token=strtok(buffer,s);
                i = atoi (token);
                printf("%d ",i);
                }

    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

3 Answers3

2

Besides changing the argument to your strtok calls in the loop, you need to change the order in which you call strtok and atoi. Right now, what if strtok in the loop returns NULL, which it will do sooner or later?

So instead do e.g.

token=strtok(buffer,s);
while (token!=NULL)
{
    i = atoi (token);
    printf("%d ",i);
    token = strtok(NULL, " ");
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You need to check the token for NULL before first atoi() itself. Alongside, usage of strtol() is preferred over atoi().

That said, I think, to serve your purpose,

while (token!=NULL)
            {token=strtok(buffer,s);

should be

while (token!=NULL)
            {token=strtok(NULL,s);

Otherwise, you'll end up parsing the input from starting over and over again.

Next, to avoid the \n read by fgets(), use delimiter string like

 char * s = " \n";
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

As per the man page of strtok():

The strtok() function parses a string into a sequence of tokens. On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

char *strtok(char *str, const char *delim);

So modify your while loop as follows (Look at the order of atoi() and strtok() function calls):

while (token!=NULL)
{
i = atoi (token);
printf("%d ",i);
token=strtok(NULL,s);
}

You can also use strtol which is obviously better than atoi.

Community
  • 1
  • 1
Deepak Uniyal
  • 89
  • 3
  • 16