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

reading from an input line with ""

I have this program that is supposed to read a line e.g post "nice job" john and i want to get every token in that line but for some reason i only get some of them.

Expected output:

post
nice job
john

My output:

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

post
nice

im sure im putting the correct format on sscanf so whats the problem i dont get why it doenst consider "nice job" as one word.

Program:

#include <stdio.h>

int main()
{
    char token1[128];
    char token2[128];
    char token3[128];
    char str[] = "post \"nice job\" john";
    sscanf(str,"%s \"%s\" %s",token1,token2,token3);
    puts(token1);
    puts(token2);
    puts(token3);
   return(0);
}

>Solution :

The second %s reads "nice" because %s stops at the first whitespace. The format string then demands a match for a " quote, which isn’t next (a space is next). The scanf functions don’t skip input until a match is found, they stall. Always check the return value which should have been 3.

This code

#include <stdio.h>
    
int main()
{
    char token1[128] = "";
    char token2[128] = "";
    char token3[128] = "";
    char str[] = "post \"nice job\" john";
    int res = sscanf(str, "%s \"%[^\"]\"%s", token1, token2, token3);
    printf("%d\n", res);
    puts(token1);
    puts(token2);
    puts(token3);
    return(0);
}

outputs

3
post
nice job
john
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