我用 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/