简体   繁体   中英

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.

As you can see, someone told me to fix it using <cstdio> , but I don't understand what's happening.

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.

So, I want to know why is this happening, and how can I prevent it without using <cstdio> (if possible).

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.

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]

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).

That is because the cin >> n1; instruction reads just enough of your stdin stream to get the number, but it doesn't also "eat" the new line. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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