我想运行代码,直到用户不输入choice = 'n',如果choice = 'n',那么程序执行将停止

1hdlvixo  于 2023-08-03  发布在  其他
关注(0)|答案(2)|浏览(78)
#include <stdio.h>
#include <stdlib.h>
void main()
{
    char choice = 'y';
    while(choice != 'n')
    {
        printf("Enter choice(y/n):- \n");
        scanf("%c", choice);
        if(choice == 'y')
        {
            printf("Choice = y");
        }
        if (choice == 'n')
        {
            printf("Choice = n");
            exit(1);
        }
    }
}

字符串

实际输出:

Enter choice(y/n):- 
y
(Program execution terminated)

预期输出:

Enter choice(y/n):-
y
Enter choice(y/n):-
y
Enter choice(y/n):-
n
(Program execution terminated)


我想询问用户选择,直到他/她不按“n”。这是我的问题

mhd8tkvw

mhd8tkvw1#

代码中的问题是scanf。使用scanf阅读字符时,需要使用格式说明符%c,并使用&运算符提供存储字符的变量的地址:

#include <stdio.h>
#include <stdlib.h>

int main() // Changed from 'void' to 'int' as it is a good practice to return an integer from main
{
    char choice = 'y';
    while (choice != 'n')
    {
        printf("Enter choice(y/n):- \n");
        scanf(" %c", &choice); // Note the space before %c to consume any leading whitespace

        if (choice == 'y')
        {
            printf("Choice = y\n");
        }
        else if (choice == 'n') // Use 'else if' to check for 'n' after checking for 'y'
        {
            printf("Choice = n\n");
            exit(0); // Use exit(0) to indicate successful termination
        }
    }
    return 0; // Return 0 from main to indicate successful execution
}

字符串

6ie5vjzr

6ie5vjzr2#

#include <stdio.h>
#include <stdlib.h>
void main()
{
 char choice;
 do
  {
    printf("Enter choice(y/n):- \n");
    scanf(" %c", &choice);
    if(choice == 'y')
    {
        printf("Choice = y\n");
    }
    else if (choice == 'n')
    {
        printf("Choice = n");
        exit(0);
    }
  }while(choice != 'n');
}

字符串

相关问题