我试图在我的C代码中进行while循环
像这样:
main()
{
char q ;
while( a == 'yes' )
{
/* my code */
printf("enter no to exit or yes to continue");
scanf("%s",q);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我输入字符"q"....控制台崩溃了
并停止工作
我在while循环中错了什么?
你无法比较字符串a == 'yes'.你需要使用strcmp功能.
你需要这样的东西:
int main(int argc, char **argv)
{
char a[200];
strcpy(a, "yes");
while( !strcmp(a, "yes") )
{
/* my code */
printf("enter no to exit or yes to continue");
scanf("%s",a);
}
}
Run Code Online (Sandbox Code Playgroud)
有几个错误:
"yes"不是'yes'.scanf期望变量的地址:scanf("%s", &q)不scanf("%s", q).char q[4]),而不是字符一(char q).a条件中引用的变量while( a == 'yes').'\n'打印之前被缓冲.所以你可能需要的是:
#include <stdio.h>
#include <string.h>
#define INP_SIZE 3
int main() {
char inp[INP_SIZE + 1] = { 0 };
while (strcmp(inp, "yes")) {
printf("enter yes to continue or whatever else to exit\n");
scanf("%3s", inp);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
PS我想构建一个格式字符串以避免重复3,但我的懒惰赢了.
| 归档时间: |
|
| 查看次数: |
376 次 |
| 最近记录: |