This question already has answers here:
Using getline(cin, s) after cin [duplicate]
(13 answers)
Closed 7 years ago.
I have some code:
I wish to take in an ID, make sure it's of 8 chars in length, make sure each digit is a number, and continue to ask until they give the correct input. BEFORE SOMEONE MARKS THIS DOWN, i researched and tried to look at answers given :c
I don't get why it says the id I enter 00000002 is an Invalid ID according to my code. It's not working. can anyone help?
void Student::getData(){
string id_;
cout << "lastName?" << endl;
cin >> lastName;
cout << "firstName?" << endl;
cin >> firstName;
cout << "ID?" << endl;
while(getline(cin,id_) && id_.size() != 8){
cout << "Invalid ID" << endl;
}
while(getline(cin,id_) && id_.size() != 8){
Here getline() just gets the newline left over from the previous line of input. Add a line to ignore the rest of the line before that.
cin.ingore(std::numeric_limits<std::streamsize>::max(), '\n');
while(getline(cin,id_) && id_.size() != 8){
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Hey so I only started C++ 2 days ago, so please try to keep the answer simple, otherwise probably won't understand it, thanks!
I tried to make a basic program where a program asks for a word, then counts the letters in said word. It then tells asks if you want to know the letter in any given position of the letter. Im making this because I thought I would learn better if I just tried making something basic rather than endlessly watching videos on it.
I ran into a problem with the asking the user part of the code. I want to have it check whether the user typed Y or N, and if neither, repeat asking until either Y or N is inputted. I tried using goto, but I could not get it to work despite checking online tutorials on how it should work. If anyone could help that would be greatly appreciated :).
When run, it does the following: enter image description here
The code is below, thank you for reading:
#include <string>
using namespace std;
int main(){
string text; //variable for the word to be measured
int letter; //variable for the placement of the letter in word
string confirmation; //variable for Y or N
cout << "This program counts letters in a word \n\n";
cout << " Please type a word for me to count: \n\n";
cin >> text;
cout << "\nYour word has " << text.length() << " letter";
if (text.length()>1){
cout << "s"; // Checks whether to put an s at the end of the prev. sentence for a plural or not
}
cout << "\n\nThis is what you typed by the way: " << text << "\n\n";
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
check:
if (confirmation == "Y"){ //Loops until one of these are fulfilled
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else if (confirmation == "N"){
cout << "\nAlright have a nice day";
} else {
goto check;
}
return 0;
}
First, goto-Syntax is something you do not need to learn as a beginner. In 99.99% there are better alternatives than using goto, so until you are very advanced, just pretend that goto does not exist in C++.
Second, the goto in your code works. It is just that if the user answers something different than "Y" or "N", your code will infinitely loop between the label check: and the goto check statement, as there is no way that confirmation can change in between.
Last, here is an example how to better do this, using a while-loop.
cout << "Would you like me to find the letter in any given position in the word? \n\n If yes, type Y. If no, type N: \n\n";
cin >> confirmation;
while (confirmation != "Y" && confirmation != "N") { //Loops until one of these are fulfilled
cout << "Please answer Y or N.\n";
cin >> confirmation;
}
if (confirmation == "Y"){
cout << "What position's letter would you like me to find? \n\n";
cin >> letter;
cout << "\n" << text[letter-1] << "\n\n";
cout << "Thanks for using me, have a nice day";
} else {
cout << "\nAlright have a nice day";
}
This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Using getline() in C++
(7 answers)
Closed 4 years ago.
Can anyone explain why I am having trouble with the below C++ code?
#include <iostream>
using namespace std;
class stud
{
public:
string name,adrs;
long long unsigned int mob;
};
int main()
{
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
for(int i = 0; i < num; i++)
{
cout << endl << "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin, s[i].name); // this line skips some data before even they are
//entered and there is no error while compiling
}
system("CLS");
for(int i = 0; i < num; i++)
{
cout << endl << " Student " << i+1 << " name is: ";
cout << s[i].name << endl;
}
return 0;
}
When I try to input a string value for an object in the array as above, using getline() without any delimiter (which uses a new line by default), I don't get correct output since some other data is automatically being skipped.
But, when I use getline() as follows instead of above, it works fine, but it needs a delimiter at the end:
getline(cin, s[i].name, '.');
Please help me find a solution. I think the Enter key is pressed several times at one key press, and that's why the getline() skips some data. I'm not sure about this, though.
before correcting you program one thing to know is that
Actually, a newline is always appended to your input when you select Enter or Return when submitting from a terminal.
cin>> doesn't remove new lines from the buffer when the user presses Enter.
This has little to do with the input you provided yourself but rather with the default behaviour std::getline() exhibits. When you provided your input for the name (std::cin >> num;), you not only submitted the following characters, but also an implicit newline was appended to the stream, getline() mistakes this for user input along with enter.
It is recommended to use cin.ignore() to get rid of those extra characters after using cin>>(whatever) if you are going to use getline(cin,any string) later.
Edit this part of your code:
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
cin.ignore();//just add this line in your program after getting num value through cin
//fflush(stdin);
//cin.sync();
//getchar();
for(int i = 0; i < num; i++)
{
cout<<endl<< "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin,s[i].name);
}
system("CLS");
you can use and may be tempted to use fflush(stdin) also but it is not recommended as it has undefined behaviour, as
According to the standard, fflush can only be used with output buffers, and obviously stdin isn't one.
about cin.sync():
using “cin.sync()” after the “cin” statement discards all that is left in buffer. Though “cin.sync()” does not work in all implementations (According to C++11 and above standards).
you can also use getchar() to get the newline caused by Enter
This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 7 years ago.
I am trying to code a little game-like adventure program, and I need if else statements in it for it to work correctly. However, whenever I run this if else statement, it does not output what I want.
#include <iostream>
using namespace std;
int main()
{
while(true)
{
cout << endl << "What will you do?: ";
string input;
cin >> input;
if (input == "Nothing" || input == "nothing")
{
cout << "Why would you do nothing?" << endl;
}
else if (input == "Look North" || input == "Look north" || input == "look North" || input == "look north")
{
cout << "You look north. There is nothing north." << endl;
}
}
}
What I expect it to output would be this:
What will you do?: nothing
Why would you do nothing?
What will you do?: look north
You look north. There is nothing north.
What will you do?:
But instead of getting that when I put those as an input, I get this:
What will you do?: nothing
Why would you do nothing?
What will you do?: look north
What will you do?:
What will you do?:
I would like some help on resolving this issue, as I cannot find an answer to why this would be happening.
cin >> input;
does not read whitespaces. You need to use std::getline.
getline(cin, input);
Because when you input "Look north"
using
cin>>input;
only "Look" is saved into the input variable ..
The problem is withcin statement as it does not handle white spaces, try what is posted here. Also, you will find helpfull the tolower() function, to normalize your inputs.
This question already has answers here:
getline not asking for input? [duplicate]
(3 answers)
Closed 9 years ago.
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else
{
system("cls");
cout << "Your message has to be between 1 and 500 characters long...";
goto prot;
}
So, whenever I get to this piece of code, it's like it automatically presses return, and "skips" the getline() function (AKA, goes to the prot label). The same thing happens further up for some reason. However, after a bit of experimenting, I've found out that when using this:
input:
if (special == 0)
{
cout << "Choose your input message below:\n";
getline(cin, inp);
if (inp.length() > 0 && inp.length() < 500) {}
else
{
system("cls");
cout << "Your message needs to be between 1 and 500 characters long\n";
goto input;
}
}
It does work the second time (with other words, after going to the input label). The difference between these two codes is that the first one has to bypass a std::cin code before getting back to getline(), while the other one doesn't.
A solution and some explaination would be gladly appreciated.
The following works for me:
#include <iostream>
#include <string>
int main() {
std::string str;
start:
std::cout << "prompt:\n";
std::getline(std::cin, str);
if (0 < str.length() && str.length() < 20) {}
else {
std::cout << "invalid.\n";
goto start;
}
std::cout << "input: \"" << str << "\"\n";
}
How is yours different from this?