output the whole string in c++ using getline - c++

I wrote this code. It works in the main function
cout << "Enter the patron's name: ";
getline(std::cin, patron.name);
cout << "Enter the book title: ";
getline(std::cin, book.title);
cout << book.title << " is now checked out to " << patron.name << endl;
However, when I put it under a do while loop with switch case, it does not work anymore.
do {
cout << endl << "? "; cin >> choice;
switch (toupper(choice)){
case 'T':
cout << "Enter the patron's name: ";
getline(std::cin, patron.name);
cout << "Enter the book title: ";
getline(std::cin, book.title);
cout << book.title << " is now checked out to " << patron.name << endl;
break;
}[enter image description here][1]
} while (choice != 'Q' && choice!= 'q');
The input was like:
Could anyone explain to me why this happened? Thanks

After this statement
cout << endl << "? "; cin >> choice;
insert
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
to remove the new line character (that corresponds to the pressed Enter key after the input) that is still in the input buffer, Otherwise a call of getline will read an empty string.
You should include the header <limits> to use the class numeric_limits

This \n after T(your input) is being consumed by getline. That's why you are getting such behaviour. You need to flush the newline out of the buffer.
You can do this by adding this statement as shown.
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Enter the patron's name: ";

Related

No output is shown when option 2 is chosen in C++

So after I enter my input in option 1, then I chose to continue. My input information are gone when choosing the option 2.
I just started my programming course so please give me a lot of advice.
This is the output enter image description here
struct Human
{
string name;
string foods;
string date;
};
char option;
int main()
{
do
{
int user;
cout << "You" <<endl;
cout << "\nChoose one from the menu below" <<endl;
cout << "1 Enter information" <<endl;
cout << "2 See information stored" <<endl;
cout << "\nEnter your option" <<endl;
cin >> user;
Human me;
switch(user)
{
case 1:
{
cin.ignore(100, '\n');
cout << "\nEnter your name: ";
getline(cin, me.name, '\n');
cout << "Enter your favorite foods: ";
getline(cin, me.foods, '\n');
cout << "Enter your birthday: ";
getline(cin, me.date, '\n');
break;
}
case 2:
{
cin.ignore(100, '\n');
cout << "Your name is: " << me.name<<endl;
cout << "Your favorite foods are: " <<me.foods<<endl;
cout << "Your birthday is: " <<me.date<<endl;
break;
}
}
cout << "\nDo you wish to continue?" <<endl;
cout << "Enter 'y' to continue and 'n' to exit" <<endl;
cout << "Your choice:";
cin >> option;
}while(option == 'y');
return 0;
}
You create a new Human me; in every iteration of the do-while loop. When you read input for that me in one iteration, the me in the next iteration won't know about that.
Read about "scope" and moving the declaration Human me; outside of the loop will probably do what you expect.
#include<iostream>
using namespace std;
struct Human
{
string name;
string foods;
string date;
};
char option;
int main()
{
Human me;
do
{
int user;
cout << "You" <<endl;
cout << "\nChoose one from the menu below" <<endl;
cout << "1 Enter information" <<endl;
cout << "2 See information stored" <<endl;
cout << "\nEnter your option" <<endl;
cin >> user;
switch(user)
{
case 1:
{
cin.ignore(100, '\n');
cout << "\nEnter your name: ";
getline(cin, me.name, '\n');
cout << "Enter your favorite foods: ";
getline(cin, me.foods, '\n');
cout << "Enter your birthday: ";
getline(cin, me.date, '\n');
break;
}
case 2:
{
cin.ignore(100, '\n');
cout << "Your name is: " << me.name<<endl;
cout << "Your favorite foods are: " <<me.foods<<endl;
cout << "Your birthday is: " <<me.date<<endl;
break;
}
}
cout << "\nDo you wish to continue?" <<endl;
cout << "Enter 'y' to continue and 'n' to exit" <<endl;
cout << "Your choice:";
cin >> option;
}while(option == 'y');
return 0;
}
So, Here is The Working Code problem is that you declare struct variable in the loop so every time loop runs it gets again initialized and previous lost
enter image description here

C++ - How to know where to put cin.ignore

I have a code from my friend and we do not know how to use cin. ignore very well.
Our problem is that we are using do while and at the end of loop we want to ask user to enter if he wants to again enter some values as you will see from the code itself.
If the answer is 'y' then he can "write" again but the problem is we are using getline and we have the problem with the first getline in this loop. The program does not recognise it after the first time use.
Here is the code:
int main() {
ofstream datoteka("podaci.txt", ios::app);
if (datoteka.fail()) {
cout << "Ne postojeca datoteka";
exit(1);
}
string ime;
string prezime;
char pol;
int godiste;
float prosjek;
char odluka;
do{
system("CLS");
cout << "Unesite ime: ";
getline(cin, ime);
datoteka << ime;
cout << "Unesite prezime: ";
getline(cin, prezime);
datoteka << " " << prezime;
cout << "Unesite pol(M - musko, Z - zensko): ";
cin >> pol;
datoteka << " " << pol;
cout << "Unesite godiste: ";
cin >> godiste;
datoteka << " " << godiste;
cout << "Unesite prosjek: ";
cin >> prosjek;
datoteka << " " << prosjek << endl;
cout << endl;
cout << "Da li zelite unijeti podatke za jos jednu osobu?" << endl;
cout << "[Y] za da, [N] za ne : ";
cin >> odluka;
} while (odluka != 'N' || odluka !='n');
The problem is with the
getline(cin,ime);
It wont recognize it after the first time use.
Can someone help me?
The basic problem is that this code mixes two different forms of input. Stream extractors (operator>>) do formatted input; they skip whitespace, then try to interpret non-whitespace characters, and stop when they encounter something that doesn't fit with what they're looking for. That works fine when you have multiple extractors: std::cin >> x >> y >> z;,
getline() is an unformatted input function; it grabs whatever is in the input stream, up to the first newline.
If you mix them you can get into trouble. The usual way to get around this is to call some variation of cin.ignore() when you switch from formatted to unformatted input, and that's where the code in the question goes astray.
At the end of the loop, the code calls std::cin >> odluka;. That reads one character from the console, and leaves any additional input in place. Since the console itself typically will sit waiting for characters until it sees a newline character, typing that single character also requires hitting the Enter key, which puts a newline into the input stream. The extractor leaves the newline there. When the loop repeats, the code calls std::getline(std::cin, ime), which sees the newline character and stops reading input.
So whenever you transition from formatted input to unformatted input you have to clear out any remnants from the previous input efforts.
Or you can always read a line at a time, and parse the input yourself.
i'm not sure exactly what the problem is. i took your code and it does what it's supposed to be doing on my machine (made a few adjustments so i can understand what's going on):
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace::std;
int main() {
ofstream datoteka("podaci.txt", ios::app);
if (datoteka.fail()) {
cout << "Ne postojeca datoteka";
exit(1);
}
string ime;
string prezime;
char pol;
int godiste;
float prosjek;
// changed it to a char pointer
char odluka[] = { "Y" };
do{
system("CLS");
cout << "1: ";
getline(cin, ime);
datoteka << ime;
cout << "2: ";
getline(cin, prezime);
datoteka << " " << prezime;
cout << "3: ";
cin >> pol;
datoteka << " " << pol;
cout << "4: ";
cin >> godiste;
datoteka << " " << godiste;
cout << "5: ";
cin >> prosjek;
datoteka << " " << prosjek << endl;
cout << endl;
cout << "6" << endl;
cout << "[Y], [N]: ";
cin >> odluka;
// added this. it was not waiting for my input properly.
cin.get();
// print results
system("cls");
printf("results (press any key to move on)\n\n1: %s\n2: %s\n3: %c\n4: %d\n5: %.02f\n6: %c\n\n", ime.c_str(), prezime.c_str(), pol, godiste, prosjek, odluka);
getchar();
} while (_stricmp(odluka, "n")); // while "odluka" is not "n" or "N" (the _stricmp is not case-sensitive so they both return the same result)
system("cls");
printf("press any key to exit!\n");
getchar();
getchar();
}
here is the output from "podaci.txt":
test1 test1 1 1 1.1
test2 test2 2 2 2.2
consider using scanf/sprintf/printf with c strings in the future if this keeps malfunctioning perhaps?

Use of getline to read a string with white spaces in a structure

I want to read strings with white spaces into members of a structure. Tried using getline but both the output statements are clubbed with a single cin for both. As per the similar posts here, tried using cin.ignore, but the input is not read into the member of the structure. Pls help. It's a part of my assignment and I'm a beginner in C++. This is how my code looks like:
#include <string.h>
using namespace std;
struct book {
string title, author;
int no_of_pages, year;
float price;
};
int main() {
int N;
cout << "Enter the no. of books whose details are to be entered:" << endl;
cin >> N;
book b[N];
int x;
for (x = 0; x < N; x++) {
cout << "Enter the title of book #" << x + 1 << ":" << endl;
getline(cin, (b[x].title));
// cin.ignore();
cin.ignore(1000, '\n');
cout << "Enter the author's name:" << endl;
getline(cin, (b[x].author));
cout << "Enter the no. of pages:" << endl;
cin >> b[x].no_of_pages;
cout << "Enter the price of book:" << endl;
cin >> b[x].price;
cout << "Enter the year of publishing" << endl;
cin >> b[x].year;
}
for (x = 0; x < N; x++) {
cout << "\n\n";
cout << "The details of book" << x + 1 << " are:" << endl;
cout << "Title :" << b[x].title << endl;
cout << "Author :" << b[x].author << endl;
cout << "No. of pages :" << b[x].no_of_pages << endl;
cout << "Price :" << b[x].price << endl;
cout << "Publishing year:" << b[x].year << endl;
cout << "---------------------------------------------";
}
return 0;
}
There's no point in using cin.ignore() in between two calls to getline. ignore is used to discard remaining characters after numeric input. So the place to use it is after numeric input and before the next getline. Like this
cout << "Enter the title of book #" << x + 1 << ":" << endl;
getline(cin, (b[x].title));
cout << "Enter the author's name:" << endl;
getline(cin, (b[x].author));
cout << "Enter the no. of pages:" << endl;
cin >> b[x].no_of_pages;
cout << "Enter the price of book:" << endl;
cin >> b[x].price;
cout << "Enter the year of publishing" << endl;
cin >> b[x].year;
cin.ignore(1000, '\n');
That said I would just read everything using getline, then convert the strings to numbers where needed. That's simpler and cleaner, all you need to know is how to convert a string to an integer, which you can easily research for yourself.
There are two places you should put cin.ignore in your code:
cout << "Enter the no. of books whose details are to be entered:" << endl;
cin >> N;
// First cin.ignore here
cin.ignore(1000, '\n');
cout << "Enter the year of publishing" << endl;
cin >> b[x].year;
// Second cin.ignore here
cin.ignore(1000, '\n');
Besides this I see two more problems in your code:
#include <string> not <string.h>
add #include <iostream>
Why cin.ignore is necessary? User is expected to provide new line ('\n') delimited input. When getline is used, it leaves the input stream in such a state that the next attempt to read input from stream will start at next line. This is not true for operator >>. What int x; cin >> x; does here is it reads only the integer not the new line character present right after the integer. Hence, the next attempt to read will continue within the same line. getline will then find no character before new line and hence will fetch an empty string. To avoid this and to effectively start reading from the next line, cin.ignore is necessary.

"getline" prompt gets skipped, not working as intended

Here are my codes:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age1;
int age2;
string name1;
string name2;
cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
if ( (age1 <= 100 || age2 <= 100) && (age1 < age2) )
{
cout << name1 << " is younger!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 > age2) )
{
cout << name2 << " is younder!" << "\n";
}
else if ( (age1 <= 100 || age2 <= 100) && (age1 = age2) )
{
cout << name1 << " and " << name2 << " are of the same age!" << "\n";
}
else
{
cout << "You've got some really old people that are well older than 100!";
}
}
The first getline and cin works fine. I am able to be prompted to input.
However, the second getline and cin are prompted at once, thus I can only input for cin. (The second getline is skipped!)
If I use four cins, the program will work properly.
cin >> age1; does not read the newline character following the number. The newline remains in the input buffer, then prematurely stops the second getline.
So, your program already works as long as you enter the first age and the second name on the same line.
One solution would be to skip whitespace after the numbers:
cin >> age1 >> ws;
Live demo.
first: cin>>age; It takes the number and stores into age but at the same
time it leaves the newline character in the buffer itself. so when there is prompt for next name cin finds that left over newline character in the buffer and takes it as the input. that it why it escapes the name2 prompt.
cout << "Please enter the name for one people: " << "\n";
cin>>name1;
cout << "Please enter the age for this people: " << "\n";
cin >> age1;<<--**this left the new line character in input buffer**
cin.get();<<-- **get that newline charachter out of there first**
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
now i give name1-> shishir age1->28
name2->ccr age-> 22 it prints ccr is younder!<-- the spelling is wrong too :D
for more info on getline and get() read c++ primer plus listing 4.3, 4.4, 4.5
Happy coding
You need a ; after getline (cin, name);
hope this helps
I would suggest using cin.ignore(100,'\n'). It ignores the amount of characters you specify when you call it(100 in the example above), up to the char you specify as a breakpoint. For example:
cout << "Please enter the name for one people: " << "\n";
getline (cin, name1);
cout << "Please enter the age for this people: " << "\n";
cin >> age1;
cin.ignore(100, '\n');
cout << "Please enter the name for another people: " << "\n";
getline (cin, name2);
cout << "Please enter the age for this people too: " << "\n";
cin >> age2;
cin.ignore(100, '\n');

Using cin function

The following code doesn't give the second prompt to "enter message". How do I fix it?
cout << "Enter shifts:" << endl;
cin >> shifts;
cout << "Enter message:" << endl;
getline(cin, msg);
try this one
cout << "Enter shifts:" << endl;
cin >> shifts;
cout << "Enter message:" << endl;
cin.ignore();
getline(cin, msg);
use cin.ignore(); before using getline anywhere.
when you enter shifts there is a newline which read by geline funtion. So You need to ignore that newline.
write :
cout << "Enter shifts:" << endl;
cin >> shifts;
getchar();
cout << "Enter message:" << endl;
getline(cin, msg);