我有以下使用 Visual Studio 的控制台 Win32 应用程序的“C”代码。它检查参数并直接调用函数或使用 scanf()
获取输入,然后调用该函数。如果我提供命令行参数,该程序可以完美运行,但是当我使用 scanf()
提供输入时,它可能会添加一个我想避免的额外换行符。
我知道它这样做是因为当我给出参数时,在显示“按 ENTER 退出...”后,它会等待 ENTER 输入,但在使用 scanf()
时不会这样做>。如果我也使用 scanf_s()
就会出现这个问题。
感谢您对此的帮助。
问候,
沙希德
unsigned long int ipv;
unsigned int yrs;
float acr, acl, asp, irr, psp;
if(argc<=1) {
//get inputs
printf("Initial value of portfolio: "); scanf("%lu", &ipv);
printf("Average cash rate: "); scanf("%f", &acr);
printf("Average cost of living: "); scanf("%f", &acl);
printf("Average return for share portfolio: "); scanf("%f", &asp);
printf("Initial removal for living expenses: "); scanf("%f", &irr);
printf("Percentage of shares in initial portfolio: "); scanf("%f", &psp);
printf("Years for the analysis: "); scanf("%u", &yrs);
//simulate the investment with given inputs
simulate(ipv, acr, acl, asp, irr, psp, yrs);
} else {
if (argc == 8) {
//invsim 1000000 0.05 0.036 0.12 0.08 0.5 20
//simulate the investment with given inputs
simulate(atol(argv[1]), (float)atof(argv[2]), (float)atof(argv[3]), (float)atof(argv[4]), (float)atof(argv[5]), (float)atof(argv[6]), atoi(argv[7]));
} else {
printf("Please enter arguments as...\ninvsim.exe ipv acr acl asp irr psp yrs");
}
}
printf("\n\nPress ENTER to quit...");
getchar();
最佳答案
要改进“暂停”功能,请使用以下更新:
printf("\n\nPress ENTER to quit...");
while( getchar() != '\n' ); // clear the input buffer after reading numbers with scanf
getchar(); // wait for new input
编辑:
考虑到您程序的if-else
,将建议的while
循环移动到上面:
printf("Years for the analysis: ");
scanf("%u", &yrs);
while( getchar() != '\n' ); // clear the input buffer
关于c++ - C - 使用 scanf() 时额外的换行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29161052/