c++ - C - 使用 scanf() 时额外的换行输入

标签 c++ c visual-studio scanf

我有以下使用 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/

相关文章:

c++ - 我的类有一个 toString() 方法,我如何使用它在 std::unordered_set 中进行散列?

c++ - 关于特定接口(interface)类型的模板分支

c - 动态结构内存之间的指针

c - 为什么 argc 和 argv 的地址相差 12 个字节?

eclipse - 在 Visual Studio 中是否等同于 Eclipse "Run Configurations"?

c++ - 如何在C++中创建日志文件

c - 如何用C实现XOR加密从客户端发送数据到服务器

c++ - 我该如何解决这个错误? CRT 检测到应用程序在堆缓冲区结束后写入内存

visual-studio - 从 Visual Studio Web 安装项目中排除文件

Java 在 C++ 中的 "public static final Object"