C++ program ignoring the first character after the first input - c++

Here is the code in the main class where I am asking for input.
Class in(nameOfClass, numOfStudents);
for (int i = 0; i < numOfStudents; i++)
{
cout << "\nEnter the name of student " << i + 1 << ": ";
string studentName = "";
cin.ignore();
getline(cin, studentName);
cout << "\n ~ Enter the grades for " << studentName << endl;
cout << " ~ (Use this format: 3 - 100 100 100)" << endl;
cout << " ~ ";
string gradeLine = "";
getline(cin, gradeLine);
Student stu = Student(studentName, gradeLine); in .addStudent(i, stu);
cout << endl;
}
For the first run of the loop, the studentName reads in all the characters including spaces since I used getline(cin, studentName);. If I input "Andrew", then studentName will read in "Andrew".
However, for all further runs of the loops, if I input "Andrew" for the name of the student, the program stores "ndrew" into the studentName variable. I tried using cin.ignore(), cin.clear(), and cin.sync() in different places in the loop, but it stops the input and I need to enter a '\n' for it to to keep going and ask for the next student's information.
How do I clear the buffer after the loop is done so that my next run on the loop reads all the characters, but the loop does not pause and waits for the user to enter '\n'?

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;

c++ Program skips through lines while taking input [console application]

I am writing a sequential program on Library Management System which consists of two structs (books and student) and several functions.
Everything works accordingly except when I try to take console input in the function add_new_book() for the struct book , it skips line while taking input. I did research previously and then used the function cin.ignore() . That function works for the first two string inputs but after taking first two inputs, it skips the remaining input lines and terminates the function.
Here below is code from struct book and function add_new_book()
struct books{
int book_id;
string book_name;
string author_name;
string subject;
int fine;
};
void add_new_book(){
struct books b;
cout << "Enter the Book Name : ";
getline(cin, b.book_name);
cin.ignore();
//cin >> b.book_name;
cout << "Enter Author's Name : ";
getline(cin, b.author_name);
cin.ignore();
cout << "Enter Book id : ";
cin >> b.book_id;
cout << "Enter Book Cost : ";
cin >> b.fine;
cin.ignore();
cout << "Enter the Subject : ";
getline(cin, b.subject);
cout << "\n",b.book_name,b.author_name,b.book_id,b.fine,b.subject;
cout << "\n\n\t\t SUCCUSSFULLY ADDED \n";
// open a file in write mode.
ofstream outfile;
outfile.open("book1.txt");
outfile << b.book_name << endl;
outfile.close();
admin();
}
I suggest to get rid of cin.ignore's and use getline for numeric fields as well, using a std::string as a temporary buffer:
string s;
cout << "Enter Book id : ";
//cin >> b.book_id;
getline(cin, s);
Once you have the user input in a string, check its value and eventually assign it to the struct field, e.g. the book id has to be converted to int, this way:
b.book_id = std::atoi(s.c_str());
atoi will return zero if no conversion can be performed
if(b.book_id == 0)
{
cout << "Invalid book id";
}
Also, cout is not meant to be used the way you do. I would try something clean and tidy, like this:
cout << "Title : " << b.book_name << endl;
cout << "Author: " << b.author_name << endl;
//etc ...
You you shouldn't call std::cin.ignore() after std::getline(). getline will extract the '\n' from the input stream at the end of the line. Calling ignore will extract and discard another line.

Program ignores the first letter of input

I've seen other questions about this problem but I can't seem to incorporate those in my problem right here.
My Code
cout << "Get User's input\n";
for (int i = 0; i < size; i++)
{
cout << "Enter the author's name: ";
cin.ignore();
getline(cin,a[i].name); // Ariel the Mermaid
cout << endl;
for (int count = 0; count < size; count++)
{
cout << "Enter Title " << count + 1 << " : ";
cin.ignore();
getline(cin,a[i].books[count].title); // Intro to Me
if (a[i].books[count].title == "NONE")
break;
cout << "Enter Price " << count + 1 << " : $";
cin >> a[i].books[count].price; // 49.99
}
cout << endl;
}
When I have inputted "Ariel the Mermaid", it gives me "riel the Mermaid" when I cout it. Also the "Intro to Me" gives "ntro to Me".
What's the problem with this code?
You are skipping the first character with cin.ignore().
A good use of cin.ignore() is when you have cin >> before a getline()
for example:
cout << "Digit you age" << endl;
cin >> age;
cout << "Digit your full Name" << endl;
cin.ignore();
getline(cin,name);
This happens because when the compiler reachs the cin will make a stop to read from the keyboard until you pressed the enter key to finish, then the getline() will capture the last character wich is a "\n". So you have to cin.ignore() to ignore that last character.
Your call to cin.ignore() is ignoring one character. This method ignores a count of n characters provided as an argument. The default n is 1.
You should delete the line with cin.ignore ().

"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');

C++ Won't Accept # symbol in object string? Seems to be address issue maybe?

I am so lost. I am having an issue with the following code when saving and loading data to a binary file. I have a very similar/exact piece of code that works with a different object. I think it has something to do with the email address and the # symbol in it. Here are the important functions.
/* This is my save to file function */
FILE *file=fopen("patronsave","wb");
fwrite(&buffer,sizeof(buffer),1,file);
for(int i=0;i<3;i++){
Patron_Class *ppointer = new Patron_Class();
cout << "\n" << endl;
ppointer->save(file);
}
fclose(file);
That is the function I use to save my objects to a file.
Here is my code that I am using to load the file:
vector<Patron_Class*> Patron_Entries;
FILE *file=fopen("patronsave","rb");
fread(&buffer,sizeof(buffer),1,file);
printf("Buffer: %d\n",buffer);
for(int i=0;i<buffer;i++){
Patron_Class *pointer2 =new Patron_Class(file);
Patron_Entries.push_back(pointer2);
Patron_Entries[i] -> print();
system("pause");
}
fclose(file);
If I run the save function and then immediatly run the load function it works, but if I only run the load function it crashes when it tried to load the email. Here is my class and object code:
class Patron_Class{
public:
long patron_id;
string F_name;
string L_name;
long phone_num;
string email;
string street_address;
string city;
string state;
int zip_code;
Patron_Class(){
cout << "Please enter a new ID" << endl;
cin >> patron_id;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a First name" << endl;
cin >> F_name;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a last name" << endl;
cin >> L_name;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a phone number" << endl;
cin >> phone_num;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a email" << endl;
cin >> email;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a street address" << endl;
cin >> street_address;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a city" << endl;
cin >> city;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a State via it's initials" << endl;
cin >> state;
cin.ignore(1000, '\n');
system("cls");
cout << "Please enter a zip code" << endl;
cin >> zip_code;
cin.ignore(1000, '\n');
system("cls");
cout << "You have created a new patron named: " << F_name << " " << L_name << endl;
}
Patron_Class(FILE *inputfile){
fread(&patron_id, sizeof(patron_id),1,inputfile);
fread(&F_name, sizeof(F_name),1,inputfile);
fread(&L_name, sizeof(L_name),1,inputfile);
fread(&phone_num, sizeof(phone_num),1,inputfile);
fread(&email, sizeof(email),1,inputfile);
fread(&street_address, sizeof(street_address),1,inputfile);
fread(&city, sizeof(city),1,inputfile);
fread(&state, sizeof(state),1,inputfile);
fread(&zip_code, sizeof(zip_code),1,inputfile);
}
void print(){
cout << patron_id << " " << F_name << " " << L_name << " " << phone_num << " " << email << " " << street_address << " " << city << " " << state << " " << zip_code << "\n" << endl;
}
void save(FILE *inputFile){
fwrite(&patron_id, sizeof(patron_id),1,inputFile);
fwrite(&F_name, sizeof(F_name),1,inputFile);
fwrite(&L_name, sizeof(L_name),1,inputFile);
fwrite(&phone_num, sizeof(phone_num),1,inputFile);
fwrite(&email, sizeof(email),1,inputFile);
fwrite(&street_address, sizeof(street_address),1,inputFile);
fwrite(&city, sizeof(city),1,inputFile);
fwrite(&state, sizeof(state),1,inputFile);
fwrite(&zip_code, sizeof(zip_code),1,inputFile);
}
};
Does anyone know why it might be crashing?
This is CLEARLY wrong:
string F_name;
...
fread(&F_name, sizeof(F_name),1,inputfile);
...
fwrite(&F_name, sizeof(F_name),1,inputFile);
[The same applies to all the other strings in your PatronClass - I'm using the first one for this example]
The class std::string will look something like this (for illustration purposes, the exact implementation involves several layers, some templates, and other stuff, so this is simplified for the purposes of the explanation to follow):
class string
{
char *str;
int len;
public:
...
};
So, when you do fread from the file and fwrite to the file, you are reading/writing the char *str; and int len; members from/to the file.
Let's say we start your program from scratch, with no data in the file, and we use the Patron_Class() constructor. So we read in an id, and then the F_name from the console. Let's say we enter Charles. So somehow the string class will allocate 8 bytes of memory, at the address of 0x600018. So string::str == 0x600018 and len = 8 - at location 6000018 in the heap are the letters C h a r l e s \0 [ spaces just to illustrate they are in separate memory locations]. Now we save this to a file. So the file contains 00600018 00000008. Now we stop the program and start it again, using the PatronClass(file) constructor. The heap is completely empty. We load the file data, so string::str = 0x600018 and len = 8, but that locaton 0x600018 does not contain C h a r l e s \0, but whatever the heap normally is filed with when the heap is initialized [quite likely 0]. So no wonder your name doesn't appear.
Now, the exact behaviour of your actual program is probably not the same as what I've described above, but it will NOT work right. No way, never, ever. No matter what characters you have or haven't got in names, email addresses or any other string in your code. The only reason it may APPEAR to work is that the data is still, for the most part, there in the heap, and it seems to be working because it doesn't get overwritten by something else in your case.