String manipulation with whitespaces

Viewed 60

I have to input a string and to get from it the course Id and the course name.

my code for this is:

char word[200];
    int id=0;
    char *ptrWord;
    scanf("%[^\n]", word);
    printf("%s\n", word);
    id = strtol(word, &ptrWord, 10);

these are examples of a valid input.

89110 Computer Science 101
89210 Advanced Programming 1
 89111   OOP 101

My question is, how to get rid of the spaces after the id ? for example, the course name of the last input is OOP 101, but using this method i get the whitespaces before the name, and i don't want them.

1 Answers

If your format string contains a whitespace character, scanf will discard whitespace in the input stream at that position. So use the following code:

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

You can use it only if you are sure your input file is formatted correctly.

This code will fail if the field is empty - then scanf will get confused and discard the newline character \n while trying to discard all whitespace - you cannot tell it to discard only normal spaces.

Related