Why does the program end when I enter a number? - c++

I began programming on C++ some days ago and something is really getting me troubles:
whenever I enter the number, the program ends.
Code:
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get();
return 0;
}
I need some help here so my programs could run right.
By right I mean to output the number after ending... but it just ends after I enter the number and press enter It does not print it.
UPDATE:
For the sake of the ones who didn't understood what I was meaning (sorry for my english)
Ok let me explain.
-So the program is suposed to get the values from the keyboard right.
-I enter a number let´s say is 6, ok now I press enter.
-Alright now the number is supposed to be output on the screen, but this doesn´t happen because the program closes too fast.
But this was solved actually, by adding a second cin.get(); or by adding a cin.ignore(); after each data input petition.

Here's a slightly improved version that might be closer to what you wanted:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
int n;
std::string line;
while (true)
{
std::cout << "Please enter an integer: ";
if (!(std::getline(std::cin, line))) { return 1; /* error! */ }
std::istringstream iss(line);
if (iss >> n) { break; }
}
std::cout << "Thank you. You said: " << n
<< "\n\nPlease press Enter to quit.";
std::getline(std::cin, line);
}
The error condition in the getline is triggered when the input stream is closed or otherwise terminated before another line could be read (e.g. if you hit Ctrl-D on the console). The token extraction into n fails until you enter a valid integer, and the loop will continue looping until this happens.

All you need to do is consume the newline that is left over after reading the integer.
This happens in java as well.
using namespace std;
int main()
{
int entry;
cout << "Write a number: ";
cin >> entry;
cout << entry;
cin.get(); //Consume newline
cin.get();
return 0;
}

get() reads one and only one character from the stream, so it's perfectly normal that the program ends after you enter your number.
Have a look either at the std::basic_istream<>::getline() method or, easier, std::getline() which doesn't require a dynamic buffer.
If you need more information about basic IO in C++, you can read the following documentation : Basic Input/Output - C++
Update
Like stated in the comments, I missunderstood the question, I was initially thinking that only one digit was read into the variable.
After reading carefully again, I'm unable to understand what the problem is.

The reason for this is youre using
cin.get();
return 0;
at the end of the program , the cin.get() reads the number you entered then goes straight to return 0; thus ending the program.
to stop this you can add an extra cin.get(); before return 0;
or use
system("Pause");
before return 0; instead

Related

Read string until new line in C++ without getline

I've been trying to make a program which requires me to read symbols until a new line. I saw a lot of people suggested getline() in similar problems, but
I want to know if there is any other way to do it, mainly because of the way my code works so far.
#include <iostream>
#include <string>
int main()
{
std::string str;
while(true)
{
std::cin >> str;
std::cout << str << " ";
//some actions with token
}
}
The thing I find interesting about this code is that it first reads all the inputs, and then when I press Enter, it writes them all, for example, if I input
1 2 3 a b c
I get the output after I press enter. So is there a way to use that to my advantage and only take one line of input?
You are seeing the output behavior after enter due, most likely, to the buffer being flushed. In most cases I'm aware of, this is just an artifact of how you are interacting with the stdout of your terminal, and shouldn't change how stdin is read at all.
Your best bet is definitely istream::getline, which has a great example on C++ Reference:
// istream::getline example
#include <iostream> // std::cin, std::cout
int main () {
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256);
std::cout << name << "'s favourite movie is " << title;
return 0;
}
For more information on buffer flushing, I found a decent SO question on it: What does flushing the buffer mean?

Cin not waiting for input despite cin.ignore()

I'm new to C++ and I'm using Visual Studio 2015.
cin is not waiting for input after "Please enter another integer:\n" and outputs "You entered 0" every time.
I've searched the Internet more than an hour without a solution. No combination of cin.ignore() is working. Why is the cin buffer still not cleared?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vals;
int val = 0;
int n = 0;
cout << "Please enter some integers (press a non-numerical key to stop)\n";
while (cin >> val)
vals.push_back(val);
cin.ignore(INT_MAX, '\n');
cin.ignore();
cout << "Please enter another integer:\n";
cin.ignore();
cin >> n;
cout << "You entered " << n;
system("pause");
return 0;
}
The problem is for the user to exit the loop you need to put the cin in a failed state. That is why your
while(cin >> val){ .... }
is working.
If in a failed state cin is no longer in a position to supply you with input so you need to clear() the failed state. You also need to ignore() the previously non-integer response that triggered the failed state initially.
It would also be of merit to use
if(cin >> n){
cout << "You entered " << n;
}
This will assert that a proper input for n was provided.
The problem in your program is that it expects integers, whereas a user can input anything, like a non-integer char.
A better way to do what you seem to want to do is to read characters one by one, ignoring whitespace, and if it's a digit, then continue reading to get the whole number, else stop the loop. Then you can read all chars until you reach '\n', and do the same for one number. While you do that, for each character you should check that there can still be characters in the stream with cin.eof().
Also, instead of using system("pause"), you can prevent the command line window from closing by requesting a last character before terminating the application.
Try getting your integers like this :
#include <sstream>
...
fflush(stdin);
int myNum;
string userInput = "";
getline(cin, userInput);
stringstream s (userInput);
if (s >> myNum) // try to convert the input to int (if there is any int)
vals.push_back(myNum);
without sstream you have to use try catch, so your programme won't crash when input is not an integer

Reverse String Error?

I am creating this revese string App but i get a error if i include a space in the string !
#include <iostream>
#include <string>
using namespace std;
int main()
{
int inputa;
cout<<"%%%%%%%%%%%%%%%%%%String Reversing App%%%%%%%%%%%%%%%%%%%%%%%%"<<endl<<endl;
cout<<"\nEnter 1 to continue and 0 to exit"<<endl<<endl;
cin>>inputa;
if(inputa!=0)
{
do
{
string a,c="";
cout<<"\nEnter the string you want to Reverse : ";
cin>>a;
for(int x=a.length()-1; x>=0; x--)
{
c=c+a.substr(x,1);
}
cout<<"\nThe Reverse String is : "<<c<<endl;
cout<<"\nEnter 1 to continue and 0 to exit"<<endl<<endl;
cin>>inputa;
}
while(inputa!=0);
}
//not my home work
}
If I type the following string like "abc def" there i get an error . But otherwise it works perfectly ! Is there some mistake with the codes ! I am new to CPP so it would be helpful if you could help me !
operator>> will stop reading at the first space (as David pointed out) - use getline instead
std::string a;
getline(std::cin, a);
Full edit of your code
#include <iostream>
#include <string>
#include <limits>
int main()
{
std::cout << "%%%%%%%%%%%%%%%%%%String Reversing App%%%%%%%%%%%%%%%%%%%%%%%%\n\n";
std::cout << "\nEnter 1 to continue and 0 to exit" << std::endl;
int inputa;
std::cin >> inputa;
if(std::cin && inputa!=0)
{
std::cin.ignore(std::numeric_limits<int>::max( ), '\n');
do
{
std::string a,c;
std::cout<<"\nEnter the string you want to Reverse : ";
getline(std::cin, a);
for(int x=a.length()-1; x>=0; --x)
{
c+=a[x];
}
std::cout<<"\nThe Reverse String is : " << c << std::endl;
std::cout << "\nEnter 1 to continue and 0 to exit" << std::endl << std::endl;
std::cin >> inputa;
std::cin.ignore(std::numeric_limits<int>::max( ), '\n');
}
while(std::cin && inputa!=0);
}
}
Including David's verbatim answer because he answered with much more detail (David Rodríguez - dribeas) - please +1 him before he deletes it. His answer adds much more information that I did not mention so we are merging this into a single reply at Davids request,
The answer by Adrian is correct, deals with the immediate issue and provides a solution. As to why it enters an infinite loop, the reason is that after reading the first word, you are trying to read an integer std::cin >> inputa, which will fail as cde cannot be parsed as an integer. At this point the stream enters a fail state and subsequent reads will fail without doing anything (until you clear the error state).
What should you do?
If you want to process whole lines, then you should use std::getline, rather than operator>>. Beware on mixing both, as operator>> won't consume the spaces after the read (including new lines) and you might just read an empty line with the next std::getline. You can either always read with std::getline and then parse the line, or use ignore to clear up to the newline. Finally, whenever you perform IO operations, don't expect the operation to succeed: check the state of the stream. If you don't and your loop depends on IO to complete, it is quite easy to enter this sort of infinite loop, where the stream is marked as failed, no later reads succeed and you never break out of the loop.

getline not asking for input? [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
This is probably a very simple problem but forgive me as I am new.
Here is my code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string name;
int i;
string mystr;
float price = 0;
cout << "Hello World!" << endl;
cout << "What is your name? ";
cin >> name;
cout << "Hello " << name << endl;
cout << "How old are you? ";
cin >> i;
cout << "Wow " << i << endl;
cout << "How much is that jacket? ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << price << endl;
system("pause");
return 0;
}
The problem is that when asked how much is that jacket? getline does not ask the user for input and just inputs the initial value of "0". Why is this?
You have to be careful when mixing operator>> with getline. The problem is, when you use operator>>, the user enters their data, then presses the enter key, which puts a newline character into the input buffer. Since operator>> is whitespace delimited, the newline character is not put into the variable, and it stays in the input buffer. Then, when you call getline, a newline character is the only thing it's looking for. Since that's the first thing in the buffer, it finds what it's looking for right away, and never needs to prompt the user.
Fix:
If you're going to call getline after you use operator>>, call ignore in between, or do something else to get rid of that newline character, perhaps a dummy call to getline.
Another option, and this is along the lines of what Martin was talking about, is to not use operator>> at all, and only use getline, then convert your strings to whatever datatype you need. This has a side effect of making your code more safe and robust. I would first write a function like this:
int getInt(std::istream & is)
{
std::string input;
std::getline(is,input);
// C++11 version
return stoi(input); // throws on failure
// C++98 version
/*
std::istringstream iss(input);
int i;
if (!(iss >> i)) {
// handle error somehow
}
return i;
*/
}
You can create a similar function for floats, doubles and other things. Then when you need in int, instead of this:
cin >> i;
You do this:
i = getInt(cin);
Its because you have a '\n' left lying on the input stream from a previous call.
cin >> i; // This reads the number but the '\n' you hit after the number
// is still on the input.
The easiest way to do interactive user input is to make sure each line is processed independently (as the user will hit enter after each prompt).
As a result always read a line, then process the line (until you get familiar with the streams).
std::string line;
std::getline(std::cin, line);
std::stringstream linestream(line);
// Now processes linestream.
std::string garbage;
lienstream >> i >> garbage; // You may want to check for garbage after the number.
if (!garbage.empty())
{
std::cout << "Error\n";
}
Ignore some characters until line feed is reached.
cin.ignore(256, '\n')
getline (cin,mystr);

How to validate numeric input in C++

I'd like to know how to limit an input value to signed decimals using std::cin.
double i;
//Reading the value
cin >> i;
//Numeric input validation
if(!cin.eof())
{
peeked = cin.peek();
if(peeked == 10 && cin.good())
{
//Good!
count << "i is a decimal";
}
else
{
count << "i is not a decimal";
cin.clear();
cin >> discard;
}
}
This also gives an error message with the input -1a2.0 avoiding the assignation of just -1 to i.
If the backing variable of the cin is a number, and the string provided is not a number, the return value is false, so you need a loop:
int someVal;
while(!(cin >> someVal)) {
cin.reset();
cout << "Invalid value, try again.";
}
Combining the techniques from the top answer here and this website, I get
input.h
#include <ios> // Provides ios_base::failure
#include <iostream> // Provides cin
template <typename T>
T getValidatedInput()
{
// Get input of type T
T result;
cin >> result;
// Check if the failbit has been set, meaning the beginning of the input
// was not type T. Also make sure the result is the only thing in the input
// stream, otherwise things like 2b would be a valid int.
if (cin.fail() || cin.get() != '\n')
{
// Set the error state flag back to goodbit. If you need to get the input
// again (e.g. this is in a while loop), this is essential. Otherwise, the
// failbit will stay set.
cin.clear();
// Clear the input stream using and empty while loop.
while (cin.get() != '\n')
;
// Throw an exception. Allows the caller to handle it any way you see fit
// (exit, ask for input again, etc.)
throw ios_base::failure("Invalid input.");
}
return result;
}
Usage
inputtest.cpp
#include <cstdlib> // Provides EXIT_SUCCESS
#include <iostream> // Provides cout, cerr, endl
#include "input.h" // Provides getValidatedInput<T>()
int main()
{
using namespace std;
int input;
while (true)
{
cout << "Enter an integer: ";
try
{
input = getValidatedInput<int>();
}
catch (exception e)
{
cerr << e.what() << endl;
continue;
}
break;
}
cout << "You entered: " << input << endl;
return EXIT_SUCCESS;
}
Sample run
Enter an integer: a
Invalid input.
Enter an integer: 2b
Invalid input.
Enter an integer: 3
You entered: 3.
cin's >> operator works by reading one character at a time until it hits whitespace. That will slurp the whole string -1a2.0, which is obviously not a number so the operation fails. It looks like you actually have three fields there, -1, a, and 2.0. If you separate the data by whitespace, cin will be able to read each one without problem. Just remember to read a char for the second field.
I tried many techniques for reading integer input from the user using the >> operator, but in a way or another all my experiments have failed.
Now I think that getline() function (not the method with the same name on std::istream) and the strtol() function from the include cstdlib is the only predictable consistent solution for this problem. I would appreciate if someone proved me wrong. Here is something like the one I use:
#include <iostream>
#include <cstdlib>
// #arg prompt The question to ask. Will be used again on failure.
int GetInt(const char* prompt = "? ")
{
using namespace std; // *1
while(true)
{
cout << prompt;
string s;
getline(cin,s);
char *endp = 0;
int ret = strtol(s.c_str(),&endp,10);
if(endp!=s.c_str() && !*endp)
return ret;
}
}
*1: Placing using namespace whatever; to the global scope may lead to broken "unity builds" (google!) on larger projects, so should be avoided. Practice to not use that way, even on smaller projects!
Reading integers from files is a very different matter. Raúl Roa's approach can be good for that if properly worked out. I also suggest that wrong input files should not be tolerated, but it really depends on the application.
Be warned that using >> and getline() in the same program on cin will lead to some problems. Use one of them only, or google to know how to handle the issue (not too hard).
Something like:
double a;
cin >> a;
Should read your signed "decimal" fine.
You'll need a loop and some code to make sure it handles invalid input in a sensible way.
Good luck!