首页 > 解决方案 > 如何为具有不同条件的程序获取多个输入(整数和字符串)

问题描述

我尝试以不同的方式实现此代码,但它总是会中断(最后一个条件),所以我不知道问题是什么。

它应该读取integer输入和on/off输入,然后打印正确的结果

#include <string.h>
#include <stdio.h>
int main(void) {

    printf("start");
    int c;
    char ch;
    int light_id = 1;
    //char on_off_str;
    while (light_id > 0) {

      printf("Enter number and on/off_str:\n");
      //c = getchar();
      //ch = getchar();


      if (c = getchar() == 1) {
        if (ch = getchar() == 'on')  {
          printf("1 and on");
    }
      if (ch = getchar() == 'off') {
        printf("1 and off");
    }
      }
     else if (c = getchar() == 2) {
       if (ch = getchar() == 'on') {
         printf("2 and on");
}
        if (ch = getchar() == 'off') {
        printf("2 and off");
}
  }
    else {
      printf("break\n");
      break;
  }

}
  return 0;
}

标签: c

解决方案


getchar()fgetc返回一个int(包含单个字符的字节码,或失败EOF时),不能与字符串“on”或“off”进行比较。请改用scanffgets ,并在比较字符串时使用strcmp== ,而不是.


推荐阅读