简体   繁体   English

如何在C中检测回车?

[英]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). 对于我的家庭作业,我们应该编写一个校验和,该校验和将继续显示校验和,直到检测到回车(按下Enter键)为止。 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. 我的校验和工作正常,并继续提示我将其转换为校验和的字符串,但是按Enter键后程序应该结束。 In my code, I set up a while loop that continues to calculate the checksums. 在我的代码中,我设置了一个while循环,该循环继续计算校验和。 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: 我也用scanf尝试过,我的循环看起来像:

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. gets(s)返回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. 您必须使用strcmp()比较两个字符串。

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. 您还应注意特殊情况,例如通过检查!feof(stdin)和其他读取错误(在这种情况下gets()返回NULL gets()来结束文件。

Please note that gets() will read a full line until '\\n' is encountered. 请注意, gets()将读取整行,直到遇到'\\ n'。 The '\\n' is not part of the string that is returned. '\\ n'不是返回的字符串的一部分。 So strcmp(s,"\\r\\n")!=0 will always be true. 因此strcmp(s,"\\r\\n")!=0始终为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. 在大多数情况下, stdin流在按Enter键时会插入“ \\ n”(换行或换行),而不是回车键或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. 但是也要注意,通常在stdin运行的函数只有在将新行插入到流中之后才会返回,因此在输入字符时无法显示更新的校验和。 In the loop above, an entire line will be buffered before getchar() first returns, and then all buffered characters will be updated at once. 在上面的循环中,整行将在getchar()首先返回之前进行缓冲,然后所有缓冲的字符将立即更新。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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