简体   繁体   English

我的 C++ 程序在它应该停止的时候并没有停止

[英]My C++ program doesn't stop when it's supposed to

I'm trying to learn C++, but every time I try to run my program it closes itself before you see what it has to show, even ignoring my cin << statements.我正在尝试学习 C++,但每次我尝试运行我的程序时,它都会在你看到它必须显示的内容之前自行关闭,甚至忽略我的cin <<语句。

As you can see, someone told me to fix it using <cstdio> , but I don't understand what's happening.如您所见,有人告诉我使用<cstdio>修复它,但我不明白发生了什么。

When I run this it stops at the cout << statement at the end, but if I remove one of the two functions at the end (the cin.get() or the getchar() ) it just continues past the first cin >> statement, ignoring the other function that in theory should stop the program.当我运行它时,它会在最后的cout <<语句处停止,但是如果我在最后删除两个函数中的一个( cin.get()getchar() ),它只会继续通过第一个cin >>声明,忽略理论上应该停止程序的其他 function。

So, I want to know why is this happening, and how can I prevent it without using <cstdio> (if possible).所以,我想知道为什么会发生这种情况,以及如何在不使用<cstdio>的情况下防止它(如果可能的话)。

I want to thank everyone who reads this and apologise for my bad English;我要感谢所有阅读本文的人,并为我糟糕的英语道歉; I'm still learning the language.我还在学习语言。

I'm using wxDev-C++, if it helps.如果有帮助,我正在使用 wxDev-C++。

Example code below:下面的示例代码:

#include <cstdio>
#include <iostream>
    
using namespace std;
    
int main () {
  //cin.get();
  float n1, iva = 0.21;
  cout << "ingrese un numero"; 
  cin >> n1;
  float n2 = n1 + n1 * iva;
  cout << "este es su numero despues del iva: " << n2;
  cin.get();
  getchar();
        
  return 0;
}

if i erase one of the two functions a the end (the cin.get() or the getchar()) it would just continue after the first "cin>>" statment ignoring the other function [sic]如果我删除两个函数中的一个(cin.get() 或 getchar()),它将在第一个“cin>>”语句之后继续,忽略另一个 function [原文如此]

It is very difficult to understand what you're trying to say, but this part leads me to believe you're asking why only one of those two functions isn't enough to not stop your program (ie end the main function).很难理解你想说什么,但这部分让我相信你在问为什么只有这两个函数中的一个不足以停止你的程序(即结束main函数)。

That is because the cin >> n1;那是因为cin >> n1; instruction reads just enough of your stdin stream to get the number, but it doesn't also "eat" the new line.指令仅读取您的标准输入 stream 即可获得数字,但它也不会“吃掉”新行。 So your cin.get() reads the new line that the other line didn't read, and getchar() then blocks your program until you press something else.因此,您的cin.get()会读取另一行未读取的新行,然后getchar()会阻止您的程序,直到您按下其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM