C++ STD Cin error in while loop - c++

Why when I entered the loop below and I type something the first instruction
cmdstd:getline(std::cin,cmdInput); does not read the input entered. For instance if I entered "b 8" it should display "cmd is b 8", but it skips to the next read std::getline(std::cin, input); and displays "it is b" instead
while (editingMode == TRUE) {
std::getline(std::cin, cmdInput);
istringstream cmdiss(cmdInput);
cout << "you entered: " << cmdInput <<endl;
if (cmdInput != "") {
copy(istream_iterator<string>(cmdiss),
istream_iterator<string>(),
back_inserter<vector<string> >(tokens));
std::cout << "cmd is " <<tokens.at(0) << std::endl;
}
//*************************
std::getline(std::cin, input);
istringstream iss(input);
if(input != ""){
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter<vector<string> >(tokens));
std::cout << "it is " << tokens.at(0) <<std::endl;
createInstruction(tokens);
}

Perhaps you have a newline character left in the input buffer, from an earlier input? This is a common error.
Lets say that your program first reads an integer with cin >> x, and then a line with getline(cin, cmdline). The user types an integer, followed by the ENTER key. The cin >> x will read the integer, but the ENTER key, interpreted as a newline character, will be left in the input buffer.
When your program then goes on to read a complete line with getline(cin, cmdline), it will read the very short line that consists of just that left-over newline character. This looks like the program "skips to the next read".

There's nothing wrong with the code. It just doesn't do what you think it should :) If you want to print the whole line entered rather than the first word, don't print tokens[0]; print the input line.
Both sections do the same thing:
read a line into a string
create an istream from that line
read the words from that istream into an array of strings called 'tokens'
print the first word
tokens.at(0) is the first word, obviously. check tokens.size() or iterate over tokens if you want to look for arguments like "8".

are you sure editingMode is TRUE?

The problem is mixing >> extractions with getline, leaving a newline (or other input) in the buffer. Blindly using ignore will hide logic errors, such as input of "42 abc" followed by cin >> some_int; cin.ignore(...);. What you really have to do is "extract" the blank line:
int main() {
using namespace std;
int n;
string s;
cout << "Enter a number: "
cin >> n >> blankline; // <---
if (cin) {
cout << "Enter a line of text: ";
getline(cin, s);
}
if (!cin) {
clog << "Sorry, I can't do that.\n";
return 1;
else {
cout << "Input successful, now processing values: " << n << s << '\n';
}
return 0;
}
Thankfully, this is easy:
template<class C, class T>
std::basic_istream<C,T>&
blankline(std::basic_istream<C,T>& s,
typename std::basic_istream<C,T>::char_type delim) {
if (s) {
typename std::basic_istream<C,T>::char_type input;
if (!s.get(input) && s.eof()) {
s.clear(s.eofbit);
}
else if (input != delim) {
s.putback(input);
s.setstate(s.failbit);
}
}
return s;
}
template<class C, class T>
std::basic_istream<C,T>& blankline(std::basic_istream<C,T>& s) {
blankline(s, s.widen('\n'));
return s;
}

Related

C++ ofstream write in file from input, without new line after each word

Basically I have a function, that writes into a .txt file.
The user has to input, what will be written in the file.
The problem is, every word has a new line, even tho it's written in the same line, while doing the input.
But I want it to be the way the user inputs it.
void Log_Write::WriteInLog(std::string LogFileName)
{
system("cls");
std::string input;
std::ofstream out;
out.open(LogFileName, std::fstream::app);
out << "\n\nNEW LOG ENTRY: " << getCurrentTime()<<"\n"; //
while (true)
{
system("cls");
std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ";
std::cin >> input;
if (input == "x")
break;
out << input << "\n"; // How do I change this so it doesn't create a new line for each word
}
out.close();
}
Sample Input:
1st Input:Test Input
2st Input:Next input
Sample Output in file.txt:
Test
Input
Next
Input
(Without the spaces in between!)
std::cin >> input; just reads to the first whitespace while std::getline(std::cin, input); would read the whole line.
One way of fixing it:
while(
system("cls"),
std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ",
std::getline(std::cin, input)
) {
if (input == "x")
break;
out << input << '\n';
}
I put the std::getline call last in the while condition to make the loop exit if std::getline fails.
Now, the above looks pretty nasty so I suggest putting clearing the screen and prompting the user in a separate function instead.
Example:
#include <iostream>
#include <string>
#include <string_view>
std::istream& prompt(std::string_view prompt_text, std::string& line,
std::istream& in = std::cin,
std::ostream& out = std::cout) {
std::system("cls");
out << prompt_text;
std::getline(in, line);
return in;
}
void Log_Write::WriteInLog(std::string LogFileName) {
// ...
auto prompt_text = "Writing in Log\n\n"
"Type 'x' to leave editor!\n\n"
"Insert new entry: ";
while (prompt(prompt_text, input)) {
if (input == "x") break;
out << input << '\n';
}
}

Ending an input stream with a specified character, such as '|'?

Currently learning C++, newbie.
I have an issue when ending the input with the '|' character, my program skips to the end/ends and does not allow for further input. I believe it is because std::cin is in an error state due to inputting a char when expecting an int, so i have tried to use std::cin.clear() and std::cin.ignore() to clear the issue and allow the remainder of the programme to run but I still cannot seem to crack it, any advice appreciated.
int main()
{
std::vector<int> numbers{};
int input{};
char endWith{ '|' };
std::cout << "please enter some integers and press " << endWith << " to stop!\n";
while (std::cin >> input)
{
if (std::cin >> input)
{
numbers.push_back(input);
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
}
And then pass the vector to a function to iterate through x amount of times and add each element to a total, but the program always skips past the user input:
std::cout << "Enter the amount of integers you want to sum!\n";
int x{};
int total{};
std::cin >> x;
for (int i{ 0 }; i < x; ++i)
{
total += print[i];
}
std::cout << "The total of the first " << x << " numbers is " << total;
Please help!
When the use enters a "|" (or anything that is not an int), the loop ends and the error handling that is inside the loop does not execute. Just move the error code to outside the loop. Also, you read from stdin twice which will skip every other int.
while (std::cin >> input) {
numbers.push_back(input);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Note: If you want to specifically check for "|" can change to something like this:
while (true) {
if (std::cin >> input) {
numbers.push_back(input);
}
else {
// Clear error state
std::cin.clear();
char c;
// Read single char
std::cin >> c;
if (c == '|') break;
// else what to do if it is not an int or "|"??
}
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

When I repeat the program it skips array entry [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I need the following program to take the entire line of user input and put it into string names:
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);
With the cin >> number command before the getline() command however (which I'm guessing is the issue), it won't allow me to input names. Why?
I heard something about a cin.clear() command, but I have no idea how this works or why this is even necessary.
cout << "Enter the number: ";
int number;
cin >> number;
cin.ignore(256, '\n'); // remaining input characters up to the next newline character
// are ignored
cout << "Enter names: ";
string names;
getline(cin, names);
Another way of doing it is to put a
cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
after your cin>>number; to flush the input buffer completely (rejecting all of the extra characters until a newline is found). You need to #include <limits> to get the max() method.
cout << "Enter the number: ";
int number;
if (cin >> number)
{
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout << "Enter names: ";
string name;
// keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
while (getline(cin, name))
...use name...
}
else
{
std::cerr << "ERROR reading number\n";
exit(EXIT_FAILURE);
}
In the code above, this bit...
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
...checks the rest of the input line after the number contains only whitespace.
Why not just use ignore?
That's pretty verbose, so using ignore on the stream after >> x is an oft-recommended alternative way to discard content through to the next newline, but it risks throwing away non-whitespace content and in doing so, overlooking corrupt data in the file. You may or may not care, depending on whether the file's content's trusted, how important it is to avoid processing corrupt data etc..
So when would you use clear and ignore?
So, std::cin.clear() (and std::cin.ignore()) isn't necessary for this, but is useful for removing error state. For example, if you want to give the user many chances to enter a valid number.
int x;
while (std::cout << "Enter a number: " &&
!(std::cin >> x))
{
if (std::cin.eof())
{
std::cerr << "ERROR unexpected EOF\n";
exit(EXIT_FAILURE);
}
std::cin.clear(); // clear bad/fail/eof flags
// have to ignore non-numeric character that caused cin >> x to
// fail or there's no chance of it working next time; for "cin" it's
// common to remove the entire suspect line and re-prompt the user for
// input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
Can't it be simpler with skipws or similar?
Another simple but half-baked alternative to ignore for your original requirement is using std::skipws to skip any amount of whitespace before reading lines...
if (std::cin >> number >> std::skipws)
{
while (getline(std::cin, name))
...
...but if it gets input like "1E6" (e.g. some scientist trying to input 1,000,000 but C++ only supports that notation for floating point numbers) won't accept that, you'd end up with number set to 1, and E6 read as the first value of name. Separately, if you had a valid number followed by one or more blank lines, those lines would be silently ignored.
Try:
int number;
cin >> number;
char firstCharacterOfNames;
cin >> firstCharacterOfNames; // This will discard all leading white space.
// including new-line if there happen to be any.
cin.unget(); // Put back the first character of the name.
std::string names;
std::getline(cin, names); // Read the names;
Alternatively. If you know that number and names will always be on different lines.
cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(cin, names);
You can use std::ws to extract any whitespace characters in the input buffer before using getline. Header for std::ws is sstream.
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);
Try cin.ignore() when you use cin before getline() function
void inputstu(){
cout << "Enter roll Number:";
cin >> roll_no;
cin.ignore(); //ignore the withspace and enter key
cout << "Enter name:";
getline(cin, stu_name);
}
Or you can flush the input buffer to read the string
fflush(stdin)
it is defined in header stdio.h.
This code works..
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
fflush(stdin); //FLUSHING STDIN
getline(cin, names);
i just used
getline(cin >> ws,lard.i_npute);
with the standard
#include <iostream>
header in the instances where I was having problems with carriage returns and the ws manipulator worked. I will probably start embedding looping functions as classes and using constructor and destructor calls atleast.
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);//works on the \n left behind
getline(cin, names);//continues and rewrites names
its pretty self explainatory, there is a \n left behind in the stream that cin >> number uses, which gets assigned to names the first time its used. Reusing the getline writes the correct value now.
You can find the answer you want in cppreference.
When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.
you want to use cin.ignore() after your cin statements because you want to ignore the "\n" left in the buffer after taking your int variable with cin.
i have a similar program i used with a similar problem:
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.
int n;
double d2;
string str;
// Read and save an integer, double, and String to your variables.
cin >> n;
cin >> d2;
cin.ignore();
getline(cin, str);
// Print the sum of both integer variables on a new line.
cout << i + n << endl;
// Print the sum of the double variables on a new line.
cout << d + d2 << endl;
// Concatenate and print the String variables on a new line
cout << s << str << endl;
// The 's' variable above should be printed first.
return 0;
}
Conceptually, I think you want each answer to be neatly one line. So why don't you try this?
cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);
cout << "Enter names: ";
string names;
getline(cin, names);
The code consumes the first newline character correctly, gives you the number if the line is correct or throws an exception if it is not. All for free!
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
// USE peek() TO SOLVE IT! ;)
if (cin.peek() == '\n') {
cin.ignore(1 /*numeric_limits<streamsize>::max()*/, '\n');
}
getline(cin, names);
return 0;
}
Just peek ahead using cin.peek() and see if a '\n' is still left in cin's internal buffer. If so: ignore it (basically skip over it)

Reading Vector string [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I need the following program to take the entire line of user input and put it into string names:
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);
With the cin >> number command before the getline() command however (which I'm guessing is the issue), it won't allow me to input names. Why?
I heard something about a cin.clear() command, but I have no idea how this works or why this is even necessary.
cout << "Enter the number: ";
int number;
cin >> number;
cin.ignore(256, '\n'); // remaining input characters up to the next newline character
// are ignored
cout << "Enter names: ";
string names;
getline(cin, names);
Another way of doing it is to put a
cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
after your cin>>number; to flush the input buffer completely (rejecting all of the extra characters until a newline is found). You need to #include <limits> to get the max() method.
cout << "Enter the number: ";
int number;
if (cin >> number)
{
// throw away the rest of the line
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
cout << "Enter names: ";
string name;
// keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
while (getline(cin, name))
...use name...
}
else
{
std::cerr << "ERROR reading number\n";
exit(EXIT_FAILURE);
}
In the code above, this bit...
char c;
while (cin.get(c) && c != '\n')
if (!std::isspace(c))
{
std::cerr << "ERROR unexpected character '" << c << "' found\n";
exit(EXIT_FAILURE);
}
...checks the rest of the input line after the number contains only whitespace.
Why not just use ignore?
That's pretty verbose, so using ignore on the stream after >> x is an oft-recommended alternative way to discard content through to the next newline, but it risks throwing away non-whitespace content and in doing so, overlooking corrupt data in the file. You may or may not care, depending on whether the file's content's trusted, how important it is to avoid processing corrupt data etc..
So when would you use clear and ignore?
So, std::cin.clear() (and std::cin.ignore()) isn't necessary for this, but is useful for removing error state. For example, if you want to give the user many chances to enter a valid number.
int x;
while (std::cout << "Enter a number: " &&
!(std::cin >> x))
{
if (std::cin.eof())
{
std::cerr << "ERROR unexpected EOF\n";
exit(EXIT_FAILURE);
}
std::cin.clear(); // clear bad/fail/eof flags
// have to ignore non-numeric character that caused cin >> x to
// fail or there's no chance of it working next time; for "cin" it's
// common to remove the entire suspect line and re-prompt the user for
// input.
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
}
Can't it be simpler with skipws or similar?
Another simple but half-baked alternative to ignore for your original requirement is using std::skipws to skip any amount of whitespace before reading lines...
if (std::cin >> number >> std::skipws)
{
while (getline(std::cin, name))
...
...but if it gets input like "1E6" (e.g. some scientist trying to input 1,000,000 but C++ only supports that notation for floating point numbers) won't accept that, you'd end up with number set to 1, and E6 read as the first value of name. Separately, if you had a valid number followed by one or more blank lines, those lines would be silently ignored.
Try:
int number;
cin >> number;
char firstCharacterOfNames;
cin >> firstCharacterOfNames; // This will discard all leading white space.
// including new-line if there happen to be any.
cin.unget(); // Put back the first character of the name.
std::string names;
std::getline(cin, names); // Read the names;
Alternatively. If you know that number and names will always be on different lines.
cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(cin, names);
You can use std::ws to extract any whitespace characters in the input buffer before using getline. Header for std::ws is sstream.
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);
Try cin.ignore() when you use cin before getline() function
void inputstu(){
cout << "Enter roll Number:";
cin >> roll_no;
cin.ignore(); //ignore the withspace and enter key
cout << "Enter name:";
getline(cin, stu_name);
}
Or you can flush the input buffer to read the string
fflush(stdin)
it is defined in header stdio.h.
This code works..
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
fflush(stdin); //FLUSHING STDIN
getline(cin, names);
i just used
getline(cin >> ws,lard.i_npute);
with the standard
#include <iostream>
header in the instances where I was having problems with carriage returns and the ws manipulator worked. I will probably start embedding looping functions as classes and using constructor and destructor calls atleast.
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);//works on the \n left behind
getline(cin, names);//continues and rewrites names
its pretty self explainatory, there is a \n left behind in the stream that cin >> number uses, which gets assigned to names the first time its used. Reusing the getline writes the correct value now.
You can find the answer you want in cppreference.
When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.
you want to use cin.ignore() after your cin statements because you want to ignore the "\n" left in the buffer after taking your int variable with cin.
i have a similar program i used with a similar problem:
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
int i = 4;
double d = 4.0;
string s = "HackerRank ";
// Declare second integer, double, and String variables.
int n;
double d2;
string str;
// Read and save an integer, double, and String to your variables.
cin >> n;
cin >> d2;
cin.ignore();
getline(cin, str);
// Print the sum of both integer variables on a new line.
cout << i + n << endl;
// Print the sum of the double variables on a new line.
cout << d + d2 << endl;
// Concatenate and print the String variables on a new line
cout << s << str << endl;
// The 's' variable above should be printed first.
return 0;
}
Conceptually, I think you want each answer to be neatly one line. So why don't you try this?
cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);
cout << "Enter names: ";
string names;
getline(cin, names);
The code consumes the first newline character correctly, gives you the number if the line is correct or throws an exception if it is not. All for free!
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
// USE peek() TO SOLVE IT! ;)
if (cin.peek() == '\n') {
cin.ignore(1 /*numeric_limits<streamsize>::max()*/, '\n');
}
getline(cin, names);
return 0;
}
Just peek ahead using cin.peek() and see if a '\n' is still left in cin's internal buffer. If so: ignore it (basically skip over it)

Why is a space in the string making my code loop infinitely? [duplicate]

This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 6 years ago.
I have the following code which simply takes a string and find each character's index in the alphabet.
void encrypt()
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
string word;
vector<char> temp;
char a, b;
cout << "Enter string to encrypt: \n";
cin >> word;
for (int i=0; i<word.length(); i++)
{
bool t = false;
a = word[i];
for (int j=0; j<alpha.length(); j++)
{
b = alpha[j];
if (a == b)
{
cout << a << "'s index = " << j+1 << endl;
t = true;
}
}
if (t == false)
{
cout << "space here\n";
}
}
}
when i input a word/string with no space the code works fine but when i input a string with a space the program goes into an infinite loop.
edit main() added due to request:
main()
{
int a;
bool b = false;
while (b == false)
{
cout << "1. Encrypt a string\n";
cout << "2. Decrypt a string\n";
cout << "3. Exit\n";
cout << endl;
cin >> a;
cout << endl;
if (a == 1)
{
encrypt();
}
else if (a == 2)
{
decrypt();
}
else if (a == 3)
{
b = true;
}
}
return 0;
}
cin >> word;
will read only the first word and leave the second word in the input stream. After that, the call
cin >> a;
will result in an error unless the second word starts with a number. Once the program enters a state of error, nothing is read and the program stays in a loop.
To diagnose problems like these, always check the state of the stream after a read operation.
if ( cin >> word )
{
// Use word
}
else
{
// Deal with error.
}
if ( cin >> a )
{
// Use a
}
else
{
// Deal with error.
}
To address your real problem, don't use operator>> to read space separated string. Use getline (and use a variable name different from word).
std::string str;
if ( getline(std::cin, str) )
{
// Use str
}
else
{
// Deal with error.
}
However, in order to use getline successfully, you have to make sure that after a is read, you ignore the rest of the line. Otherwise, the rest of the line will be read by getline.
if ( cin >> a )
{
// Ignore rest of the line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Use a
}
else
{
// Deal with error.
}
Replace cin >> word; with getline(cin, word);. It will accept a line as input. Which will resolves your input containing spaces.
As far as infinite loop concern, clear the error bits on the stream cin.clear();
You can check whether cin is accepting the space separated string completely, by doing a cout instantly after the cin. If cin is not accepting the space separated string, then try using getline
Issue resolved:
Use the following:
cout << "Enter string to encrypt: ";
scanf(" %[^\n]s",word);
for (int i=0; word[i]!='\0'; i++)
{
use
include <cstdio>
Hope this solves the problem!! I will get back to you with the solution using string..