C : Process keeps exiting before being able to input anything

标签 c char c-strings strcmp toupper

我在使用下面的代码时遇到了问题。在我输入响应 [y/n] 之前,它就退出了程序。我在我的编译器中没有看到任何错误,所以我很难解决这个问题。

   srand(time(NULL));  
    int nGid; //guest id
    char opt1;
    printf(" Hello Guest! do you have an id number [Y/N]?");
    scanf("%c", &opt1);

    opt1 = toupper(opt1);
  //asks for guest id
    if (strcmp(opt1, 'Y') == 0){
        printf("Please enter id: \n");
        scanf("%d", &nGid);
    }
  //generates random id number
    else {
        nGid = rand()%100;
        printf("Your guest id is : %d", nGid);
  return 0;
}

感谢您的帮助!

最佳答案

strcmp 采用空终止的 char *,但您传递的是 char 作为参数。

您可以使用== 运算符直接比较两个char

改变。

if (strcmp(opt1, 'Y') == 0){

if (opt1 == 'Y'){

关于C : Process keeps exiting before being able to input anything,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58729014/

相关文章:

c - 我是否必须对 SQLITE 中的 argv 回调中的每个参数进行深度复制?

c++ - 将字符串复制到 char 数组

c - 从 C 中的 *char[] 变量获取第一个字符

C:通过外部 malloc 从函数更新运行时定义的二维数组

C:Do-While 循环重复太多!

无法使用 VB 从 C 函数读取 char *

c - 将每个偶数对字符与数组中的下一对字符交换

c - 遍历客户端程序接收到的缓冲区

c - 循环遍历所有可能的长度为 n 的字符串

c - C语言使用malloc的访问冲突