[英]In C, how do I only accept certain strings and continue to ask the user for input until valid input is entered?
[英]how to loop user input and copy it to file until “exit” string in entered using C?
我想编写一个小程序,当最大输入为100个字符时(使用控制台)从用户那里获取字符串,当用户按下Enter键时,它将把输入复制到某个文件中。 当用户输入字符串“ exit”时,我想退出循环
例如:“嗨,你好吗?” “ bla bla”“退出”我只是不知道如何使它工作-我应该使用scanf吗? getchar? fgets?
char* buf ;
int i;
buf = (char*)calloc(100, sizeof(char));
while(1)
{
fgets(s, sizeof(s), stdin);
if (strcmp(s , "exit") == 0)
break;
else
...write to file...
}
我需要手动输入“ \\ 0”吗?
谢谢!
fgets()
很好,但是在某些实现中,它将尾随换行符( \\n
)放在行尾。 您必须删除它才能使比较生效,或者准备进行比较以接受"exit"
和"exit\\n"
:
if (strcmp(s , "exit") == 0 || strcmp(s , "exit\n") == 0)
break;
要么
fgets(s, sizeof(s), stdin);
char *p = strchr(s, '\n');
if (p) *p = 0;
if (strcmp(s , "exit") == 0)
break;
旁注:除非您打算将字符串返回给调用者函数,否则根本不需要使用calloc()
。 改用自动数组:
char s[0x100]; // or whatever
我应该使用scanf吗? getchar? fgets?
以上任何一项,但您的while
循环应转换为:读取输入时,输入不是“退出”。 您的while
循环当前转换为:世界未尽。
我建议类似:
while (fgets(s, sizeof s, stdin) == s && strcmp(s, "exit\n") != 0) {
/* ... */
}
我需要手动输入“ \\ 0”吗?
没有; 仔细选择工具可以使您使用标准字符串库处理由标准I / O库生成的字符串(对于上面的fgets
/ strcmp
代码而言),或通过其他更复杂的方法处理非字符串。
PS。 无需malloc
,并且sizeof (char)
在C中始终为 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.