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;
}
2
  • atoi segfaults on a NULL pointer. Commented Jan 15, 2015 at 9:27
  • check token != NULL before calling atoi. Currently you are calling atoi before checking for null. Commented Jan 15, 2015 at 9:38

3 Answers 3

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, " ");
}
Sign up to request clarification or add additional context in comments.

Comments

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";

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.