mixing cin and getline input issues [duplicate] - c++

This question already has answers here:
cin and getline skipping input [duplicate]
(4 answers)
Closed 7 years ago.
Im doing exercices from c++ primer, and trying to do a program that recieves as input a word and a line. If when i ask for a word (with cin) I press enter, then the program just skips the next lines and doest ask for a line (with the getline)... and if i write an entire phrase in the cin (like "hello beautifull world") then the first word ("hello") is captured by the cin and the others two words ("beautifull world") by the getline.
i understand that in the cin, when i input a space, it cuts the input. what i dont uderstand are two things:
1.- why if i end the input (in the cin) with enter it skips all the rest of code? (is there a solution for that?)
2.- why if i write an entire phrase in the cin, it assign the other two word to the getline before to execute the
cout << "enter a line" << endl;
?
Thx! sorry for my english C:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word, line;
cout << "enter a word" << endl;
cin >> word;
cout << "enter a line" << endl;
getline(cin, line);
cout << "your word is " << word << endl;
cout << "your line is " << line << endl;
return 0;
}

You need cin.ignore() between two inputs:because you need to flush the newline character out of the buffer in between.
#include <iostream>
using namespace std;
int main() {
string word, line;
cout << "enter a word" << endl;
cin >> word;
cout << "enter a line" << endl;
cin.ignore();
getline(cin,line);
cout << "your word is " << word << endl;
cout << "your line is " << line << endl;
return 0;
}
For your second answer, when you enter whole string in first cin, it takes only one word, and the rest is taken by getline and thus your program will execute without taking input from getline
Demo

Related

I am making a quiz-like program. I already wrote the string answer ="George Washington". but when the user inputted the answer, it's wrong

answer = "George";
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
cin >> player1_answer;
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
This is my code. But when the user inputted the answer as exactly as what was written in the answer variable, it outputs 'x'. But if the user inputted the same answer excluding the space between "George" and "Washington", it outputs 'check'. What should I do so that the program will accept the space in the answer inputted by the user?
I tried searching the web but I can't understand a thing. So please help me
You can simply use getline instead of cin. cin reads the user input up until the first whitespace character (most commonly newlines or spaces), but getline will read user input until they hit enter. Because of this, if you want to get user input that includes spaces, you should use getline (or something similar) instead of cin.
Instead of
cin >> player1_answer;
you should use
getline(cin, player1_answer);
By using getline, the full user input ("George Washington") get assigned to the variable player1_answer. With cin, only "George" was being used, because it stopped listening for input after the first space.
Here is a full, working code example:
#include <iostream>
using namespace std;
string answer = "George Washington";
string player1_name = "Steve";
string player1_answer;
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
getline(cin, player1_answer); //Enter "George Washington"
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
//"check"
return -1;

String phrase ends at space?

I am wringing a simple code to learn more about string. When I ran my code it would not print my last name. Can someone explain why? I used string phrase to store it and it only appears to have stored my first name. Here is the code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting;
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
cin >> phrase;
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
I used string phrase to store it and it only appears to have stored my first name.
That makes sense.
cin >> phrase;
will stop reading when it encounters a whitespace character in the input.
To read the full name you can use one of the following approaches.
Use two calls to cin >>.
std::string first_name;
std::string last_name;
cin >> first_name >> last_name;
Use getline to read the entire line. getline will read everything in a a line, including whitespace characters.
getline(cin, phrase);
When you call cin >> phrase;, it only reads the string up to the first non-space character. If you want to include spaces in your name, best goes with getline(cin,phrase);.
IMPORTANT: getline() will reads whatever it is in the stream buffer up to the first \n. It means that when you enter cin >> greeting;, if you hit ENTER, getline() will read everything before that \n that is not already read, which is NOTHING into your phrase variable, making it an empty string. An easy way out is to call getline() twice. E.g.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
cout << "Exercise 3B" << endl;
cout << "Kaitlin Stevers" << endl;
cout << "String arrays" << endl;
cout << endl;
cout << endl;
char greeting[26];
cout << "Please enter a greeting: " << endl;
cin >> greeting; //IMPORTANT: THIS ASSUME THAT GREETING IS A SINGLE WORD (NO SPACES)
cout << "The greeting you entered was: " << greeting << endl;
string phrase;
cout << "Enter your full name " << endl;
string rubbish_to_be_ignored;
getline(cin,rubbish_to_be_ignored); //this is going to read nothing
getline(cin, phrase); // read the actual name (first name and all)
cout << greeting << ", how are you today " << phrase << "?" << endl;
return 0;
}
Assuming you store that code in the file stackoverflow.cpp. Sample run:
Chip Chip#04:26:00:~ >>> g++ stackoverflow.cpp -o a.out
Chip Chip#04:26:33:~ >>> ./a.out
Exercise 3B
Kaitlin Stevers
String arrays
Please enter a greeting:
Hello
The greeting you entered was: Hello
Enter your full name
Kaitlin Stevers
Hello, how are you today Kaitlin Stevers?
Tested on ubuntu 14.04

Problems with getline() function? [duplicate]

This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 8 years ago.
I have a problem with the getline function in the code below. In the "get" info section I want to be able to store a whole sentence, but I can't make it work.
When I open up my program it just skips the input for the info.
p.s: I'm new to C++
Here is the section of the code where i have the problem (Enter the information):
void add() {
string name;
string faction;
string classe;
string race;
string info;
ofstream wowdatabase("wowdatabase.txt", ios::app);
cout << "Add a race or class" << endl;
cout << "---------------------------------------------------------" << endl;
cout << "" << endl;
cout << "Enter the name of the race or class (only small letters!):" << endl;
cin >> name;
cout << "Enter Race (Type -, if writen in name section):" << endl;
cin >> race;
cout << "Enter Class (Type -, if writen in name section):" << endl;
cin >> classe;
cout << "Enter faction (Alliance/Horde):" << endl;
cin >> faction;
cout << "Enter the information:" << endl;
getline(cin, info);
wowdatabase << name << ' ' << faction << ' ' << classe << ' ' << race << ' ' << info << endl;
wowdatabase.close();
system("CLS");
main();
}
Now it works fine =) but, when i want to output the info again it only shows the first word in the sentence?
Before this statement
getline(cin, info);
make the following call
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
To use this call you must include header <limits>.
The problem is that after executing statement
cin >> faction;
the new line character that corresponds to enetered key ENTER is in the input buffer and the next getline call reads this character.
After you read fraction an empty line character will be left over. The consequent call to getline will read it. To avoid that add a call to cin.ignore before the getline call.

Counting characters in a string

My code runs and works well the first time around, but I am having looping problems:
My code isn't counting characters that are in words
The second time around when you press "yes," it ends up printing everything out. I must have a loop in the wrong spot, but I can't find it for the life of me.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
cin >> sentence;
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
By just reading your code, it looks fine, except where you get the sentence. Using cin, it will only read until it sees a newline or a space, so if you're entering a sentence, it will read every word as a different input.
Try getline(cin, sentence) and see if that fixes the problem.
Edit: Forgot to add in: use cin.ignore() after the getline. cin reads up to, and including the line break (or space) while getline only reads up to the line break, so the line break is still in the buffer.
use
cin.ignore(); //dont forget to use cin.ignore() as it will clear all previous cin
getline(cin, sentence, '\n'); //take the sentence upto \n i.e entered is pressed
You don't have the loops wrong. What's wrong is that you are assuming that
cin >> sentence;
does something different from what it really does.
If you want to read a line of text, then do this
getline(cin, sentnence);
Your code reads a single word only.
use cin it will end with a newline or a space
eg:
when you input hello world it will get hello
and you can try
getline
it wiil end with a newline
This is working, try this.
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
char character;
string sentence;
char answer;
int cCount;
while(1) {
cout << "Enter a character to count the number of times it is in a sentence: ";
cin >> character;
cout << "Enter a sentence and to search for a specified character: ";
fflush(stdin);
getline(cin, sentence, '\n');
if(character == '\n' || sentence.empty())
{
cout << "Please enter a valid answer:\n";
break;
}
else {
cCount = count(sentence.begin(), sentence.end(), character);
cout << "Your sentence had" << " " << cCount << " " << character << " " << "character(s)" << '\n';
}
cout << "Do you wish to enter another sentence (y/n)?: \n";
cin >> answer;
if (answer == 'n'){
break;
}
}
return 0;
}
after you enter first input and enter that enter is considered as input in sentence
So, you need to flush that and after that you can scan that sentence.
Try:
cCount = count(sentence.c_str(), sentence.c_str()+sentence.length(), character);

Why does getline not result in the text I expected? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Need help with getline()
In the following code, my getline is skipped entirely and doesn't prompt for input.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main ()
{
int UserTicket[8];
int WinningNums[8];
char options;
string userName;
cout << "LITTLETON CITY LOTTO MODEL: " << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto " << endl;
cout << "q) Quit Program " << endl;
cout << "Please make a selection: " << endl;
cin >> options;
switch (options)
{
case 'q':
return 0;
break;
case '1':
{
cout << "Please enter your name please: " << endl;
getline(cin, userName);
cout << userName;
}
cin.get();
return 0;
}
}
The problem is here:
cin >> options;
You can only extract (>>) from cin when the user hits enter. So the user types 1 Enter and that line executes. Since options is a char, it extracts a single character (1) from cin and stores it in options. The Enter is still in the stdin buffer, since nothing has consumed it yet. When you get to the getline call, the first thing it sees in the buffer is the Enter, which marks the end of input, so getline immediately returns an empty string.
There's lots of ways to fix it; probably the easiest way that fits with the model you're using in your program is to tell cin to ignore the next character in its buffer:
cin >> options;
cin.ignore();