0

For my homework we are supposed to write a checksum that continues to display checksums until a carriage return is detected (Enter key is pressed). My checksum works fine and continues to prompt me for a string to convert it to a checksum, but my program is supposed to end after I press the enter key. In my code, I set up a while loop that continues to calculate the checksums. In particular I put:

while(gets(s) != "\r\n")

Where s in a string that the user has to input. I've also tried this with scanf, and my loop looked like:

while(scanf("%s",s) != '\n')

That did not work as well. Could anyone please give me some insight onto how to get this to work? Thanks

Hank G
  • 379
  • 3
  • 16
  • 4
    You cannot compare C strings with the assignment operator '='. – Martin James Nov 11 '14 at 22:04
  • http://stackoverflow.com/questions/4843640/why-is-a-a-in-c/4843651#4843651 – R Sahu Nov 11 '14 at 22:06
  • The answers are right that you need something like strcmp, but gets and scanf %s don't return the newline so the comparison will still fail. Check for an empty string instead – The Archetypal Paul Nov 11 '14 at 22:08
  • 1
    Never, ever use `gets`. Replace it with `fgets`. `gets` is a horribly dangerous function and has been deprecated. Also, `fgets` will return the newline unlike `gets` which strips it. – Carey Gregory Nov 11 '14 at 22:13

3 Answers3

0

The gets(s) returns s. Your condition compares this pointer to the adress of a constant string litteral. It will never be equal. You have to use strcmp() to compare two strings.

You should also take care of special circumstances, such as end of file by checking for !feof(stdin) and of other reading errors in which case gets() returns NULL.

Please note that gets() will read a full line until '\n' is encountered. The '\n' is not part of the string that is returned. So strcmp(s,"\r\n")!=0 will always be true.

Try:

while (!feof(stdin) && gets(s) && strcmp(s,"")) 
Christophe
  • 68,716
  • 7
  • 72
  • 138
0

In most cases the stdin stream inserts '\n' (newline or line-feed) when enter is pressed rather than carriage-return or LF+CR.

char ch ;
while( (ch = getchar()) != '\n` )
{
     // update checksum using ch here
}

However also be aware that normally functions operating on stdin do not return until a newline is inserted into the stream, so displaying an updating checksum while entering characters is not possible. In the loop above, an entire line will be buffered before getchar() first returns, and then all buffered characters will be updated at once.

Clifford
  • 88,407
  • 13
  • 85
  • 165
-1

To compare a string in C, which is actually a pointer to an array of characters, you need to individually compare the values of each character of the string.

hdante
  • 7,685
  • 3
  • 31
  • 36