I have this code
char output[1000] = "";
int numWords = 0;
int wordsRemoved = 0;
char word[50]; // word that needs to be removed
char ch; //character directly following the word being checked (always space or newline)
char check[50]; // word that is being checked
scanf("%s", word);
while(!feof(stdin)){
scanf("%s%c", check, &ch);
numWords++; //counting total words
if(strcmp(check, word) == 0){
wordsRemoved++; //counting words removed
}
if(strcmp(word, check) != 0){
strcat(output, check); //checks if word should be removed and if not appends to str
strncat(output, &ch, 1);
}else if(strcmp(word, check) == 0 && ch == '\n'){
strncat(output, &ch, 1); // supposed to print a newline if the delete word was
// on the end of a string but it gives me too many
// newlines, and not enough if I remove it
}
}
printf("%s", output); //prints new string
return 0;
which is supposed to take an input text file and read until end of file, then remove a word specified by the user and then print the new string back out
For example, the test text file I am using reads:
cs
cs hello there
hello there cs
cs
hello there cscs there cs.
cs cs cs
test
Then the output should be
hello there
hello there
hello cscs there cs.
test
but I am instead getting
hello there
hello there
hello cscs there cs.
test
As you can see, I'm very close to figuring this out, but any line that consists of just the delete word ends up with an extra unwanted newline that I cannot figure out how to circumvent
Any idea how to get around this?
Also I am still learning to code so please don't use anything crazy advanced :)
Thanks for your help