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);
------->格式字符串
答案 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;
farenheit
和celsius
未初始化。初始化后移动它,即在
scanf("%f", &fahrenheit);
和
scanf("%f", &celsius);
分别。