如何解决创建用户名功能如果根本没有输入只是按回车怎么办?
如果只输入或输入空格,我如何制作错误信息?
do
{
printf("Please enter a username: ");
scanf("%s",name);
if(name[0] == '\n')
{
printf("invalid input");
}
printf("> %s\n",name);
}
while(strlen(name) < 2 || strlen(name) > 15);
解决方法
换行符将产生一个空字符串,因此不满足格式说明符,因此 scanf()
不会返回。这是有点神秘的行为,但是:
int count = scanf( "%16[^ \n]s",name ) ;
将在用 count == 0
输入换行符或前导空格时返回。它还接受不超过 16 个字符,防止缓冲区溢出,同时允许大于 15 个字符的测试。
为了避免对同一字符串进行不必要的测试和多次调用 strlen()
:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main()
{
char name[20] = "" ;
bool name_valid = false ;
while( !name_valid )
{
printf("Please enter a username: ");
int count = scanf("%16[^ \n]",name);
size_t len = count == 0 ? 0 : strlen( name ) ;
name_valid = len > 1 && len < 16 ;
if( !name_valid )
{
int ch ;
do
{
ch = getchar() ;
} while( ch != '\n' && ch != EOF ) ;
printf("invalid input\n");
}
}
printf("> %s\n",name);
return 0;
}
请注意,在“无效输入”中,您需要删除缓冲的换行符和任何前面的垃圾。
,我个人不喜欢使用 scanf() b/c 它会导致很多麻烦并且在生产环境中使用它是不安全的。我建议改用 fgets(),这是它的工作原理:
#include <stdio.h>
#include <string.h>
int main()
{
char buffer[50];
int buffer_size = sizeof(buffer);
/* accepts string input from user */
printf("Please enter a username: ");
fgets(buffer,buffer_size,stdin);
/* then remove "\n" from the string
A newline character makes fgets stop reading,but it is considered a valid character by the function and included in the string copied to str.
*/
buffer[strcspn(buffer,"\n")] = 0;
/* check if user has entered an empty string */
/* strcmp(): compares two strings and returns 0 if comparision is true */
if ((strcmp(buffer,"")) == 0 || (strcmp(buffer," ")) == 0)
printf("I can detect that you printed nothing! \n");
else
printf("You printed: %s",buffer);
return 0;
}
仅仅为了从用户那里获取输入而要做的工作量似乎很荒谬,但这就是它在 C 中的工作方式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。