【问题标题】:C : Process keeps exiting before being able to input anythingC:进程在能够输入任何内容之前一直退出
【发布时间】:2020-03-02 20:52:59
【问题描述】:

我在使用下面的代码时遇到了问题。在我输入响应 [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;
}

感谢您的帮助!

【问题讨论】:

  • OT: strcmp() 需要两个 指针 指向 0-终止的 char-array,即两个 char*。代码通过了两个char。认真对待编译器的警告。
  • 比较两个字符只是为了opt1 == 'Y'

标签: c char c-strings strcmp toupper


【解决方案1】:

代替这种说法

scanf("%c", &opt1);

使用

scanf(" %c", &opt1);
       ^^^

一般不是

opt1 = toupper(opt1);

这样写就对了

opt1 = toupper( ( unsigned char )opt1);

否则函数调用可能有未定义的行为。

变量opt1 的类型为char。它不能包含字符串。所以你可能不会应用处理字符串的标准函数strcmp。随便写

if ( opt1 == 'Y' ){

【讨论】:

  • 出于好奇:为什么opt1 的演员阵容会阻止未定义的行为? opt1 已经属于 char 类型,并且将被隐式提升为 int,那么为什么要强制转换?
  • @AnonymousAnonymous 如果 char 类型的行为与带符号的 char 类型一样,那么由于整数提升,整数值通常可以是负数,并且调用 toupper 会导致未定义的行为。
【解决方案2】:

strcmp 采用以 null 结尾的 char *,但您将 char 作为参数传递。

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

改变。

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

if (opt1 == 'Y'){

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 2021-02-21
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    相关资源
    最近更新 更多