C语言程序仅响应首个输入提示,后续提示无法接收输入问题求助
C语言程序输入交互异常问题解决
问题现象
程序仅能响应第一个输入提示,后续输入提示直接输出,无法进行输入交互,且最终输出结果不符合预期。
原程序代码
#include <stdio.h> int main(){ // Initialize char cCurrencyA, cCurrencyB; float fCurrencyA; float fRate; // Prompt user for currency names printf("Enter a currency name: "); scanf("%c%c", &cCurrencyA, &cCurrencyB); // Prompt user for the current rate printf("Enter the rate:"); scanf("%f", &fRate); // Prompt user to enter value for currency A printf("Enter value for %c", cCurrencyA); scanf("%f", &fCurrencyA); // Convert currency A to B int nResult = fCurrencyA * fRate; // Print the result printf("%f%c is %d%c", fCurrencyA, cCurrencyA, nResult, cCurrencyB); return 0; }
运行输出
Enter a currency name:USD PHP Enter the rate: Enter value for U: 0.000000U is 0S
问题原因
- 输入缓冲区残留空白字符:第一个
scanf("%c%c")仅读取输入的前两个字符(U和S),输入中的空格、换行符会留在输入缓冲区中。后续的scanf("%f")会自动跳过空白字符,但由于缓冲区中已有空白,导致程序直接跳过输入等待,继续执行后续代码。 - 货币代码存储逻辑错误:用户输入的是三位货币代码(如
USD、PHP),但程序用单个char存储,只能读取单个字符,无法正确获取完整货币代码。 - 结果精度丢失:用
int存储汇率转换结果,会丢弃小数部分,导致精度损失。
解决方案
- 使用字符数组(字符串)存储三位货币代码,适配标准货币代码格式。
- 用
scanf("%s %s")读取两个空格分隔的货币代码,自动跳过空白字符。 - 用
float或double存储转换结果,保留小数精度。 - 若需处理单个字符输入,可在
scanf格式串前添加空格(如scanf(" %f", &fRate)),强制跳过缓冲区中的空白字符。
修改后的代码
#include <stdio.h> int main(){ // 用字符数组存储三位货币代码,预留结束符位置 char cCurrencyA[4], cCurrencyB[4]; float fCurrencyA; float fRate; float fResult; // 读取两个空格分隔的货币代码 printf("Enter two currency names (e.g. USD PHP): "); scanf("%s %s", cCurrencyA, cCurrencyB); // 读取汇率,格式串前加空格跳过缓冲区空白 printf("Enter the rate: "); scanf(" %f", &fRate); // 读取货币A的数值 printf("Enter value for %s: ", cCurrencyA); scanf(" %f", &fCurrencyA); // 计算转换结果,用float保留精度 fResult = fCurrencyA * fRate; // 输出结果 printf("%.2f%s is %.2f%s\n", fCurrencyA, cCurrencyA, fResult, cCurrencyB); return 0; }
验证运行示例
Enter two currency names (e.g. USD PHP): USD PHP Enter the rate: 56.78 Enter value for USD: 100 100.00USD is 5678.00PHP
内容的提问来源于stack exchange,提问作者Franz Zapanta
相关产品推荐
相关产品推荐

