为什么它继续在c中给我这个错误

时间:2015-06-24 06:27:39

标签: c macos

float fahrenheit;
float celsius;
float formulaf = (fahrenheit - 32.0) * 5/9;
char str[20];
float formulac = celsius * 9/5 + 32.0;
printf("Choose either fahrenheit or celsius; ");
scanf("%*s", &str);
if (strcmp(str, "fahrenheit") ==0)
{
    printf("Enter the temperature in fahrenheit: ");
    scanf("%f", &fahrenheit);
    printf("%.2f fahrenheit is %.2f celsius", fahrenheit, formulaf);
}
else
{
    printf("Enter the temperature in celsius: ");
    scanf("%f", &celsius);
    printf("%.2f celsius is %.2f fahrenheit", celsius, formulac);
}

我在xcode中对此进行了编码,我创建了标题和所有内容,这是我遇到的主要部分,它在以下代码中给出了错误,它在其他一些行中给出了断点,请帮忙我解决了这个

scanf("%*s", &s); ------->格式字符串

未使用的数据参数 这是什么意思?

2 个答案:

答案 0 :(得分:2)

如果您阅读例如this scanf reference您会看到格式字符串中的"*"修饰符表示不会使用扫描的字符串。

此外,在扫描字符串时,不应使用address-of运算符,因为字符串已经是指针。

答案 1 :(得分:1)

%*s指示scanf扫描并丢弃扫描的刺痛。编译器抱怨,因为没有使用scanf&s)的第二个参数。

您可能希望使用%s%19s(告诉scanf扫描最多19个字符+ 1个NUL终结符),以防止缓冲区溢出。

同时将scanf的第二个参数更改为s。这样做是因为%s期望char*&s的类型为char(*)[20]s转换为&s[0]char*,正好是%s所期望的。

所以scanf

scanf("%*s", &str);

应该是

scanf("%s", str);

由于上述原因。

BTW,您的代码显示未定义的行为,因为当您使用

float formulaf = (fahrenheit - 32.0) * 5/9;

float formulac = celsius * 9/5 + 32.0;

farenheitcelsius未初始化。初始化后移动它,即在

后移动它
scanf("%f", &fahrenheit);

scanf("%f", &celsius);

分别。