c++ - 我的自制小应用程序立即关闭

标签 c++ visual-studio-code

我用 C++ 编写了这个小片段,如果我打开程序,它应该总结输入,然后应该打印“Press to finish”,打印后,应用程序应该在用户输入“Enter”后关闭。问题是在添加的数字添加完毕后它已经自行关闭了。

#include <stdlib.h>
#include <stdio.h>

int multi(int a, int b){
    return a * b;
}
int main(){
    printf("Programm started \n");
    int number1;
    int number2;
    int sum;
    printf("Type two numbers: \n");
    scanf("%d %d", &number1, &number2);
    sum = multi(number1,number2);
    printf("The solution is: %d \n", sum);
    printf("Press <Return> to finish \n");
   char c = getchar();
    if(c=='\n'){
         return 0;
    }
    
    
}

最佳答案

我没有看到您在等待用户按 Enter 键:

char c = getchar();  // get the next available character
                     // If there is one then take it
                     // This only waits if there is no input available.

// This does nothing.
// If the character is '\n' it returns 0
// but if it is not the '\n character then you immediately exit
// In C++ if main does not have a final return the compiler plants
// a return 0 autoamtically so it also returns zero.
if(c=='\n'){
     return 0;
}
// implied return 0 here

所以如果我看看你的其他代码:

scanf("%d %d", &number1, &number2);

这会从输入中读取两个数字。 但是它不会读取换行符。这意味着输入流上仍然留有一个新行字符,这就是为什么末尾的 getchar() 会立即返回的原因。

更改:

scanf("%d %d\n", &number1, &number2);
 //         ^  Specifically read a newline here.
 //
 // Be careful.
 // This is not a perfect solution. If there are any other characters
 // after your numbers this will fail (so you really should do some more
 // and better processing but this will resolve your immediate problem).
 //
 // I would add a loop here (just after you read your numbers)
 // to read and discard any junk on this line (or read and error 
 // if there is junk but be OK if the only input is white space
 // terminated by a new line).

关于c++ - 我的自制小应用程序立即关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66429651/

相关文章:

javascript - 如何在 VS Code 中使用 d.ts 文件进行智能感知,类似于 NPM 方法

c++ - 查找 C++ 函数运行所需的时间

c++ - 以纳秒为单位获取本地时间

c++ - 编译时字符串数组错误

visual-studio-code - 当光标移过折叠部分时,防止 VSCode 展开代码

Typescript baseUrl 不影响 VS Code 中的模块解析

c++ - 如何按标题自动对方法进行排序?

c++ - const 引用参数和函数上下文中的 const 参数之间的区别

ios - 无法在非开发 IOS 设备上安装 flutter IOS 应用

typescript - 从泛型类获取方法的参数 - TypeScript