如何在c中进行while循环

Mah*_*oud 2 c while-loop

我试图在我的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循环中错了什么?

Pab*_*ruz 6

你无法比较字符串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)

  • 如果你输入`lasagne`会怎么样?:-) (2认同)

Ale*_*lin 5

有几个错误:

  1. 字符串文字应该用双引号括起来:"yes"不是'yes'.
  2. 字符串文字无法与字符变量进行比较.
  3. scanf期望变量的地址:scanf("%s", &q)scanf("%s", q).
  4. 显然,你需要数组变量(char q[4]),而不是字符一(char q).
  5. 未声明a条件中引用的变量while( a == 'yes').
  6. 您将不会在屏幕上显示您的消息,因为它在被'\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,但我的懒惰赢了.