Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a space from the start of a array to use strcmp

Tags:

c

Hello I am doing a looping on my code with fgets and I want that when user introduces the word "bye" the program ends, so I have a do while like this:

char buf[1000]

do{

    fgets(buf, 1000, stdin);
    
    //More code here

while(strcmp(buf, "bye")!=0);

But I have a problem that it is, when user made a space or a tab or multiple spaces before write bye the strcmp doesnt recognize him as bye, so the program only exits when users only type bye without any previous space or tab.

I want to know how can I prevent the spaces or tabs before the by word to exits if user type for example:

'     bye'
like image 998
Gonçalo Bastos Avatar asked Nov 23 '25 22:11

Gonçalo Bastos


1 Answers

fgets reads in a complete line, including any starting white spaces and also including the new line character at the end of the line. Even if a user does not enter preceding white spaces, the content of buf is likely to be "bye\n", such that buf will hardly compare equal to "bye" when using strcmp.

I'd suggest to scan the buffer for a single word using sscanf and compare this word to "bye" then. Note that scanf("%s"...) skips white space characters at the beginning of a word and stops before the first white space after the word.

   char isStopWord[20];
   isStopWord[0] = '\0';
   sscanf(buf,"%19s",isStopWord);
}
while(strcmp(isStopWord, "bye")!=0);
like image 88
Stephan Lechner Avatar answered Nov 25 '25 16:11

Stephan Lechner