[英]My little self made application closes instantly
我在 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);
这会从输入中读取两个数字。 但它不读取换行符。 这意味着您在输入 stream 上仍然有一个换行符,这就是最后的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).
当您在 scanf("%d %d", &number1, &number2); 中按回车键时 getchar 将读取换行符,因此 (c=='\n') 为真。
您可以做的是忽略 scanf 留下的新行,如下所示:
char c = getchar();
if (c == '\n') c = getchar();
if (c == '\n') {
return 0;
}
如果将c
的值打印为无符号 integer,
printf("%u\n",c);
然后你会看到它已经有一个 10 的值,这是一个换行符。 getchar
从标准输入返回下一个字符,这意味着您之前的scanf
调用在输入 stream 上仍有换行符。
scanf("%d %d\n", &number1, &number2);
将专门阅读该挂起的新行。
scanf
仅从输入缓冲区中读取您的两个输入,并在您输入前两个数字并按 Enter 时离开 '\n',稍后由getchar()
准备好。
要读取包含空格的行,不要使用 scanf("%s",....) 考虑 fgets()。
fgets(string, sizeof string, stdin);
// remove potential trailing \r\n as needed
string[strcspn(string, "\n")] = 0;
或者,您可以使用%*c
。 在此处查看实时代码。
int main(){
printf("Program started \n");
int number1;
int number2;
int sum;
printf("Type two numbers: \n");
scanf("%d %d%*c", &number1, &number2); // Add %*c here
sum = multi(number1,number2);
printf("The solution is: %d \n", sum);
printf("Press <Return> to finish \n");
char c = getchar();
printf("c: %c", c);
if(c=='\n'){
printf("hi");
return 0;
}
}
%*c
将接受但忽略任何后续字符。
如果您使用的是 i/o 流,那么这是可行的。
#include<iostream>
int main()
{
int dummy = 0;
std::cout << "Enter A number to exit" << std::endl;
std::cin >> dummy;
return 0;
}
保持 window 处于打开状态,直到您输入某些内容,任何事情都可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.