为什么在使用 scanf 读取 C 中的字符串作为输入时出现类型错误?

问题描述 投票:0回答:1
int main(){
  char repeat = 'y';
  float answer;
  char operation[6] = "1 + 4";
  do{
    printf("Enter your operation in the format <number> <operand> <number>:\n");
    do{
      scanf("%s", &operation);
      printf("%s %lu\n", operation, strlen(operation));
      if (strlen(operation) == 5){
      break;
    }
    printf("Operation not in format <number> <operand> <number>, please try again.\n");
    }while(0);
    if (repeat == 'a'){
      answer = calculate(operation, answer);
    } else {
      answer = calculate(operation, 0);
    }
    printf("The answer to your operation is: %g\n", answer);
    printf("Would you like to do another operation? [y/n]\n");
    scanf("%c", &repeat);
    do{
      printf("Would you like to do an operation on the previous answer? [y/n]\n");
      scanf("%c", &repeat);
    } while(repeat != 'a' && repeat != 'y');
  } while(repeat == 'y' || repeat == 'a');
  return 0;
}

我有一些编程经验,主要是Python,少量是Java,我想尝试学习C,所以我一直在尝试制作一个简单的计算器,但在尝试读取字符串时遇到了麻烦。编译此文件时,我收到第一个 scanf 语句的警告,内容如下: Calculator/calculator.c:46:19:警告:格式指定类型“char ”,但参数类型为“char ()[6]”[-Wformat] scanf("%s", &操作);

据我了解,下面的三行实际上与我在主函数中所做的相同,但是当这些行运行时,它们在不同的文件中以及放入我的主函数中都可以正常工作。

char str[100] = "1 + 2";
scanf("%s", str); 
printf("%s", str);

我错过了什么?

c string input scanf
1个回答
0
投票

据我了解,以下三行实际上与我在主函数中所做的相同

char str[100] = "1 + 2";
scanf("%s", str); 
printf("%s", str);

再看一遍:

scanf("%s", &operation);

在这一行中,您传递的是数组的 address 而不是数组本身。该地址的类型为

char(*)[6]
,即指向大小为 6 的
char
数组的指针。这与
%s
期望的类型
char *
不同,因此会出现错误。

顺便说一句,即使你解决了这个问题,你也不会得到想要的结果。

%s
格式说明符不会读取整行文本,而是读取一系列非空白字符。因此,如果您输入
1 + 3
,存储的字符串将为
"1"

您需要使用

fgets
来读取整行,同时确保从要读取的字符串末尾删除换行符。

© www.soinside.com 2019 - 2024. All rights reserved.