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

Why are my string tokens not getting printed? (strtok)

In this code, I’m taking a credit card number (which is datatype char) that has 12 digits that have spaces (eg: 1254 6789 4331). I want to split the string where the spaces are but when I ran the code on the command prompt, only the first 4 digits get printed (eg: 1254). There were no errors on the command prompt so I’m a little confused about why the code is not working. I would appreciate it if someone could help me, Thanks!

Code:

    '''

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

    int main() {
       char string[20];
       printf("Please enter your credit card number: ");
       scanf("%s",string);
       // Extract the first token
       char * token = strtok(string," ");
       // loop through the string to extract all other tokens
       while( token != NULL ) 
       {
          printf( " %s\n", token ); //printing each token
          token = strtok(NULL," ");
       }

       return 0;
    }

    '''

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

>Solution :

Use

       scanf("%15[^\n]",string);

hope it helps

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