scanf验证C
这实际上会验证我的用户输入只有两个元素然后是换行符吗?
char newline
scanf(" %s %s%c", out, in, &newline);
if(newline != '\n'){
error();
}
will this actually verify my users input has only two elements then a newline?
char newline
scanf(" %s %s%c", out, in, &newline);
if(newline != '\n'){
error();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须检查
scanf()
的返回状态;如果它不返回 3,则验证失败。您的检查将确保有两个“单词”(前面可能有一些空格)。第二个单词后不允许有尾随空格。请注意,如果验证失败,您可能需要“吃掉”该行的其余部分 - 如果newline
中有换行符,则不需要。You must check the return status from
scanf()
; if it does not return 3, you failed the validation. Your checks will ensure that there are two 'words' (possibly preceded by some space). You won't be allowed trailing space after the second word. Note that you might need to 'eat' the rest of the line if the validation fails - you won't if you have a newline innewline
.是的,那会起作用的。但前提是输入完全匹配:
word word
。如果用户输入与该格式不同的任何内容,例如,第二个单词和输入之间的空格,您的逻辑将失败。
另外,不应该使用 scanf 来读取这样的输入。考虑使用 fgets 读取输入和 strtok 解析数据。
Yes, that will work. But only if the input matches exactly:
word word<enter>
.If the user types anything different from that format, for instance, a space between the 2nd word and enter, your logic will fail.
Also, scanf shouldn't be used to read from the input like that. Consider using fgets to read the input and strtok to parse the data.
不!如果第二个字符串和换行符之间有一些空格字符,则
scanf
将无法正常工作。使用getc()
来实现:编辑:
添加尾随空格的大小写。
No!
scanf
will work incorrect if there are some whitespace character between second string and newline. usegetc()
for that:Edit:
Adding case for trailing whitespaces.