How to detect carriage return in C?

7.4k Views Asked by At

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

3

There are 3 best solutions below

1
On

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.

0
On

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,"")) 
0
On

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.