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



int main(){
int counter1, counter2;
char line[200] = ""; //store all words that don't need to be deleted
char deleteWord[100]; //word that needs to be deleted
char space;
char word[100];
scanf("%s", deleteWord);

while(1){
    scanf("%s",word);



    if(feof(stdin)) break;
    // increment counter of total words
        ++counter1;
    if(strcmp(word, deleteWord) == 0){
    // see if the word read in == delete word
    // increment counter of deleted words
        ++counter2;
    }
    else if(strcmp(word, " ") == 0){// space is an actual space
        strcat(line,word);
        strcat(line, " ");
    }
    else if(strcmp(word, "\n")){// space a new line \n
        strcat(line,word);
        strcat(line,"\n");



    }

}


printf("--NEW TEXT--\n%s", line);




return 0;
}

In summary, my code is supposed to remove a user input string (one or more words) from another user input string (containing or not containing the word(s)) and produce the output. The code removes the word but it adds a newline per word for each iteration. I believe it is doing this because the expression for the second "else-if" is always true. However, when I properly add the strcmp function for the second else-if statement, the code does not produce an output at all (no compiler errors - just missing input). Why is this happening and how do I do a strcmp function for a newline?

  • 2
    Did you mean to have a `== 0` in the test of your last call to `strcmp()` ? – Jeremy Friesner Feb 26 '22 at 00:15
  • First `scanf()` doesn't read '\n' character into buffer. 2. `scanf()` will get you only one word, then statement & code "my code is supposed to remove a user input string (one or more words)" doesn't match. make up your mind. I.e what if user wants to remove two different words? – जलजनक Feb 26 '22 at 00:17
  • If you want to read a whole line of input consiting of several words, instead of a single word, then you should use [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead of `scanf`. – Andreas Wenzel Feb 26 '22 at 00:41
  • 1
    Instead of checking for `feof( stdin );`, it would probably be more appropriate to check the return value of `scanf`. Otherwise, if the last line before end-of-file does not end with a `'\n'`, the loop will terminate without processing the last line. Related, but does not completely apply here: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/q/5431941/12149471) – Andreas Wenzel Feb 26 '22 at 01:00

0 Answers0