如何让测试运行器像Xcode一样识别printf的换行符?
问题场景
我编写了一段计算搬家费用的C语言代码,需求是让输入内容与printf的提示信息在同一行显示,但遇到了跨环境的格式兼容问题:
- 若保留printf语句末尾的
\n,Xcode的输出格式正常,但输入内容会和提示信息分行显示; - 若删除
\n,Xcode中输入与提示能在同一行,但测试运行器会把所有提示信息挤在同一行输出。
代码示例
#include <stdio.h> #define fixedPrice 800 #define insurance 200 #define packing 300 #define maxFreeDistance 30 #define discount 0.1 #define perFloor 75 #define costPerExtra10Km 50 int main() { int floors, age, distance; char elevator, needPacking, fragileItems; double totalCost = 0.0; /* 获取用户输入并验证 */ printf("Enter the floor number of your apartment: "); scanf(" %d", &floors); if (floors < 0) { printf("Value should be positive! "); return 1; } printf("Is there an elevator? (y/n): "); scanf(" %c", &elevator); if (elevator != 'y' && elevator != 'n') { printf("Input Error!"); return 1; } printf("Do you need packing service? (y/n): "); scanf(" %c", &needPacking); if (needPacking != 'y' && needPacking != 'n') { printf("Input Error!"); return 1; } printf("Do you have fragile items that require insurance? (y/n): "); scanf(" %c", &fragileItems); if (fragileItems != 'y' && fragileItems != 'n') { printf("Input Error!"); return 1; } printf("Enter your age: "); scanf("%d", &age); if (age < 0) { printf("Value should be positive!"); return 1; } printf("Enter the distance of the move in kilometers: "); scanf("%d", &distance); if (distance <= 0) { printf("Error Input!"); return 1; } totalCost = fixedPrice; /* 无电梯时,1楼以上每层收费75 */ if (elevator != 'y') { if (floors > 1) totalCost += (floors - 1) * perFloor; } /* 需要打包服务则收费 */ if (needPacking == 'y') totalCost += packing; /* 易碎品需要保险则收费 */ if (fragileItems == 'y') totalCost += insurance; /* 超出免费里程后,每10公里收费50 */ if (distance > maxFreeDistance) totalCost += ((distance - maxFreeDistance) / 10) * costPerExtra10Km; /* 65岁及以上用户享受9折优惠 */ if (age >= 65) totalCost *= (1 - discount); /* 输出总费用 */ printf("The total cost of your move is: %.2f", totalCost); return 0; }
输出对比
- Xcode正常输出(删除
\n后):
Enter the floor number of your apartment: 4
Is there an elevator? (y/n): n
Do you need packing service? (y/n): y
Do you have fragile items that require insurance? (y/n): y
Enter your age: 70
Enter the distance of the move in kilometers: 50
The total cost of your move is: 1462.50
- 测试运行器异常输出(删除
\n后):
Enter the floor number of your apartment: Is there an elevator? (y/n): Do you need packing service? (y/n): Do you have fragile items that require insurance? (y/n): Enter your age: Enter the distance of the move in kilometers: The total cost of your move is: 1462.50 .
解决方案
核心问题是标准输出的行缓冲机制:多数终端环境(包括Xcode)会在遇到换行符\n时自动刷新输出缓冲区,但测试运行器可能依赖行缓冲触发,当输出没有\n时,缓冲区内容不会及时输出,导致所有提示堆积。
解决方法很直接:在每个提示输入的printf之后,手动调用fflush(stdout);强制刷新输出缓冲区。这样既可以让输入内容和提示信息在同一行显示,又能确保测试运行器逐行输出提示。
修改后的关键代码片段示例:
printf("Enter the floor number of your apartment: "); fflush(stdout); // 强制刷新缓冲区,确保提示立即输出 scanf(" %d", &floors);
对所有需要用户输入的提示语句都执行上述修改,就能在Xcode和测试运行器中同时实现预期的格式效果。
内容的提问来源于stack exchange,提问作者Akh

