hey guys, so i was trying to make a code that takes user char inputs and appends to the end of a string, when the user hits enter it stops. so the problem is when i hit enter it goes to next line and i needa hit another char follow by enter to exit
1 2 3 4 5 6 7 8 9 10 11 12 13
std::cout<<"Welcome to the path reverser program.\n";
A:std::string temp="";
char input;
std::cout<<"Enter a path as a series of steps (NSEW), press enter when done: ";
std::cin>>temp;
while(std::cin>>input){
if(std::cin.get()=='\n'){
// std::cin.ignore();
break;
}
temp.push_back(input);
}
MazePath m(temp);
so after the first run is completed it was prompt the user to enter y if they wanna repeat for another path or no to exit program ... when i added the getline now when i hit yes to enter a new string it skips and goes straight back to if i want a new string
int main(){
std::cout<<"Welcome to the path reverser program.\n";
//A:std::string temp="";
//char input;
A:std::string input="";
std::cout<<"Enter a path as a series of steps (NSEW), press enter when done: ";
//std::cin>>temp;
std::getline(std::cin,input);
/*
while(std::cin>>input){
if(std::cin.get()=='\n'){
//std::cin.ignore();
break;
}
temp.push_back(input);
}*/
MazePath m(input);
m.directionsOut();
std::cout<<"The path is: "<<input<<"\n";
std::cout<<m<<"\n";
char a;
std::cout<<"Another? (Y/N)";
std::cin>>a;
if(a=='Y'||a=='y')
goto A;
elsereturn 0;
the output i got was
Welcome to the path reverser program.
Enter a path as a series of steps (NSEW), press enter when done: N
The path is: N
The reversed path is: S
Another? (Y/N)y
Enter a path as a series of steps (NSEW), press enter when done: The path is:
The reversed path is:
Another? (Y/N)y
Enter a path as a series of steps (NSEW), press enter when done: The path is:
The reversed path is:
Another? (Y/N)n
Psychic powers. After you enter 'y', the char gets set with this character, but the newline after the 'y' is still in the buffer. So getline, on the next loop iteration, still sees a newline still in the buffer, and it happily extracts an empty string.
If it doesn't sound intuitive, that's because it's not. It's a common "gotcha" that everyone runs into when they first start mixing getline and the >> extraction operator.
#include <iostream>
#include <string>
#include <limits>
int main() {
std::cout << "Welcome to the path reverser program.\n";
char a {};
do {
std::string input;
std::cout << "Enter a path as a series of steps (NSEW), press enter when done: ";
std::getline(std::cin, input);
//MazePath m(input);
//m.directionsOut();
std::cout << "The path is: " << input << "\n";
//std::cout << m << "\n";
std::cout << "Another (Y/N)? ";
std::cin >> a;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (a == 'Y' || a == 'y');
}