简体   繁体   中英

How to detect carriage return in C?

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

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

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.

要比较C中的字符串(实际上是指向字符数组的指针),您需要单独比较字符串中每个字符的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM