如何为具有不同条件的程序获取多个输入(整数和字符串)

时间:2018-09-20 05:14:20

标签: c

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

应该读取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;
}

3 个答案:

答案 0 :(得分:1)

getchar()fgetc返回单个int(包含单个字符的字节码,如果失败则返回EOF),该字符串不能与“ on”字符串进行比较。 ”或“关闭”。改为使用scanffgets,并且在比较字符串而不是==时使用strcmp

答案 1 :(得分:-1)

您的代码@Mohan中几乎没有明显的错误。

  1. c被声明为integer,并且您已经使用getchar从用户那里接受了它,而是将%dscanf一起使用。
  2. 当您需要
  3. chchar时,它被声明为string,因为它应该包含多个字符。因此将其设置为char[]

我给出了完全符合您需要的代码:

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

    printf("start\n");
    int c;
    char ch[10];
    int light_id = 1;
    //char on_off_str;
    while (light_id > 0) {

      printf("\nEnter number and on/off_str:\n");
      scanf("%d%s",&c,ch);
      if (c == 1) {
        if (strcmp(ch,"on") == 0)  {
          printf("\n1 and on");
        }
        else if (strcmp(ch,"off") == 0) {
         printf("\n1 and off");
        }
      }
      else if (c == 2) {
        if (strcmp(ch,"on") == 0) {
          printf("\n2 and on");
        }
        else if (strcmp(ch,"off") == 0) {
          printf("\n2 and off");
        }
      }
      else if((c!=1)&&(c!=2)) {
        printf("break\n");
        break;
      }
    }
  return 0;
}

答案 2 :(得分:-1)

由内而外:

字符串用引号""而非引号''书写,这些都是针对单个字符的。

if (ch = getchar() == 'on')首先评估getchar() == 'on',结果被写入ch。发生这种情况是因为==的优先级高于=。为了避免这种情况,请使用方括号。

如果要比较字符串,则应使用strcmp来比较字符串。 字符可以与==进行比较。

如果您要创建一个安全的程序来读取字符串,则可以使用fgets。您可以控制要读入char数组的字符个数,然后可以根据自己的喜好用sscanf对其进行解析。一个很大的优点是它消耗了输入流中的所有内容(包括换行符),使您可以灵活地处理它。从文件读取时,这尤其有用。

在旁注:我鼓励您正确设置代码格式并在启用所有警告的情况下进行编译

举例说明您的程序:

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

#define BUFFER_SIZE 50
int main(void)
{

    printf("start\n");
    long c = 0;
    char ch[5] = {0}, buf[BUFFER_SIZE]={0};
    char *loc;
    int light_id = 1;
    char found = 0;


    while (light_id > 0)
    {
        c= 0;
        printf("Enter number and on/off_str:\n");
        if (NULL == fgets(buf,BUFFER_SIZE,stdin))
            return EXIT_FAILURE;
        loc = buf;
        found = 0;

        //look for the first number in the string and convert it to long
        while (!found && *loc!=0 )
        {
            if (isdigit(*loc))
            {
                c = strtol(loc,&loc,10);
                found = 1;
            }
            else
            {
                loc++;
            }
        }

        while ( NULL == strchr(buf,'\n')) //check that everything until a newline is consumed
        {
            if (NULL == fgets(buf,BUFFER_SIZE,stdin))
            return EXIT_FAILURE;
        }

        if (NULL == fgets(buf,BUFFER_SIZE,stdin))
            return EXIT_FAILURE;

        strncpy(ch,buf,4); //copy a string of max 4 chars into ch, leaving the 0 at the end.

        //terminate string on new line
        loc = strchr(ch,'\n');
        if (NULL != loc)
            *loc = 0;

        if (c == 1)
        {
            if (!strcmp("on",ch)) //strcmp returns 0 when strings are equal and the is \n is appended as it is not filtered out before hand
            {
                printf("1 and on\n");
            }
            if (!strcmp("off",ch))
            {
                printf("1 and off\n");
            }
        }
        else if (c == 2)
        {
            if (!strcmp("on",ch))
            {
                printf("2 and on\n");
            }
            if (!strcmp("off",ch))
            {
                printf("2 and off\n");
            }
        }
        else
        {
            printf("break\n");
            light_id = 0; //break is not needed here as we already are at the end of the loop
        }

    }
    return 0;
}

下一步将是解析ch中的读取字符串,这样即使有人输入“ on”或类似名称,您也可以获得正确的结果。