c++ why is there still input buffer left? - c++

After my first entry, my second entery name field fills up with the input buffer from the previous entry. Why? I am even using the getline but the problem still persists. Please help me with the problem. This is question from Jumping Into C++ book .
#include <iostream>
#include <string>
using namespace std;
struct Person
{
string name;
string address;
long long int PhoneNumber;
};
void displayEntries(Person p[])
{
int enteryNumber;
cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
cin >> enteryNumber;
if(enteryNumber == 0)
{
for(int i = 0; i < 10; i++)
{
cout << "Entery Number: " << i + 1;
cout << "Name: " << p[i].name << endl;
cout << "Address: " << p[i].address << endl;
cout << "Phone Number: " << p[i].PhoneNumber << endl;
}
}
do
{
cout << "Entery Number: " << enteryNumber;
cout << "Name: " << p[enteryNumber].name << endl;
cout << "Address: " << p[enteryNumber].address << endl;
cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
} while (enteryNumber != 0);
}
int main()
{
Person p[10];
for(int i = 0; i < 10; i++)
{
cout << "Enter the details of the person\n\n";
cout << "Name: ";
getline(cin, p[i].name);
cout << "Address: ";
getline(cin, p[i].address);
cout << "Phone Number: ";
cin >> p[i].PhoneNumber;
cout << endl;
}
displayEntries(p);
return 0;
}

You can see what is happening when you read the reference for getline:
When used immediately after whitespace-delimited input, e.g. after
int n;
std::cin >> n;
getline(cin, n); //if used here
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.

cin >> p[i].PhoneNumber; only gets the number. That leaves the line ending still in the input buffer to be read the next time you try to read a line.

Related

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.

c++ how do you store a full string into a string array using getline?

After it gets the first string and first double the program doesn't get the other strings.
for (int i = 0; i< NUM_MOVIES; i++)
{
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
cin >> earnings[i];
cout << endl;
}
The second time you call getline you are actually reading a newline character because cin >> does not discard newline characters after the value it has just read.
So you end up in this cycle of reading bad data. Try this:
getline(cin >> std::ws, names[i]);
The problem is that >> doesn't read past the end of line so the following std::getline() does that instead of grabbing your next input.
You can use std::ws (absorb whitespace chars):
for (int i = 0; i< NUM_MOVIES; i++)
{
cin >> std::ws; // clear previous line
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
cin >> earnings[i];
cout << endl;
}
cin >> earnings[i];
This should correct as follows
getline(cin, earnings[i])
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
string names[10];
string earnings[10];
for (int i = 0; i< 10; i++)
{
cout << "Enter the name of the movie: ";
getline(cin, names[i]);
cout << "How much did " << names[i] << " earn <in millions>: ";
getline(cin, earnings[i]);
cout << endl;
}
cout<< names[0]<< names[1]<<"\n";
cout<<earnings[0] << earnings[1]<<"\n";
return 0;
}

C++ Cash Register Program Not using <string>

I have to write a program without using strings . Here is my code :
#include <iostream>
#include <iomanip>
using namespace std;
struct product
{
char productName[100];
double productPrice = 0;
};
const int MAX_CHAR = 101;
const int MAX_ITEM = 100;
int main()
{
product item[MAX_ITEM];
double total = 0;
int count = 0;
for (int i = 0; i < MAX_ITEM; i++)
{
cout << "Please , enter the product name(for checkout type -1) : ";
cin.get(item[i].productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
if (strcmp(item[i].productName, "-1") == 0 ) {
break;
}
else {
count++;
cout << "Please , enter the price for " << item[i].productName << " : $";
cin >> item[i].productPrice;
cin.ignore(100, '\n');
total += item[i].productPrice;
cout << endl << "Product entered : " << item[i].productName << " " << "$"
<< fixed << setprecision(2) <<item[i].productPrice << endl;
cout << "Total : $" << total << endl << endl;
}
}
cout << endl << "###############";
cout << endl << "Your Receipt : " << endl << endl;
for (int i = 0; i < count; i++) {
cout << item[i].productName << " $" << fixed << setprecision(2) << item[i].productPrice << endl;
}
cout << endl << "Total : $" << total;
cout << endl << "###############";
getchar();
getchar();
return 0;
}
I have a couple questions :
Why does the program crash if I don't use cin.ignore(100, '\n'); after cin >> item[i].productPrice; ? It's just cin without any condition, so it should not leave a new line char in input stream?
How can I check if the price doesn't contain incorrect input (so it has only decimal or floating point numbers) ?
How can I check if the name contains chars and numbers which are >0 (except -1) ?
Is it better to use cin.getline in this case ?
cin is an istream, so it should leave the newline char in the stream if you use cin.get(). I haven't tested if this is the cause of your crash but it sounds like this could give you problems.
chars are just numbers. A . is 46, the digit characters are from 48 through 57. You could read your price input into a buffer and check if you read any char that does not have one of your desired values. If you find an unwanted char, you can decide if you want to repeat the input, ignore this item or exit the program.
In your else branch, check if the first character of productName is a '-'. That way, you already ensured that productName is not -1.
cin.getline() discards the newline character, so you could avoid the use of cin.ignore().

when running program it has me enter two lines after name? help please

my program seems to want to enter two inputs for name variable instead of just entering one thing and moving on to phone number?
i'm sure its simple but can someone help me fix this please? is it something it do with the getline?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//define Car struct
struct Speaker
{
string name;
string phoneNumber;
string emailAddress;
string theme;
double fee;
};
Speaker *getSpeaker();
int main()
{
Speaker thespeaker;
thespeaker = *getSpeaker();
cout << "The speaker entered is!" << endl;
cout << thespeaker.name << endl;
cout << "phone number: " << thespeaker.phoneNumber << endl;
cout << "email: " << thespeaker.emailAddress << endl;
cout << "theme: " << thespeaker.theme << endl;
cout << "fees: " << thespeaker.fee << endl;
}
Speaker *getSpeaker()
{
Speaker *theSpeaker;
theSpeaker = new Speaker;
cout << "Please enter Speakers information" << endl;
cout << "name: " ;
getline(cin, theSpeaker->name);
cin.ignore(100, '\n');
cin.clear();
cout << theSpeaker->name;
cout << "\nphone number: ";
cin >> theSpeaker->phoneNumber;
cout << "\nEmail Address: ";
cin >> theSpeaker->emailAddress;
cout << "\nTheme: ";
cin >> theSpeaker->theme;
cout << "\nFee: ";
cin >>theSpeaker->fee;
return theSpeaker;
}
There's no need for cin.ignore();
Simply write it as:
Speaker *getSpeaker()
{
Speaker *theSpeaker;
theSpeaker = new Speaker;
cout << "Please enter Speakers information" << endl;
cout << "name: " ;
getline(cin, theSpeaker->name);
cout << theSpeaker->name;
cout << "\nphone number: ";
cin >> theSpeaker->phoneNumber;
cout << "\nEmail Address: ";
cin >> theSpeaker->emailAddress;
cout << "\nTheme: ";
cin >> theSpeaker->theme;
cout << "\nFee: ";
cin >>theSpeaker->fee;
return theSpeaker;
}

C++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}