C++ pointer runtime error - c++

I made a program using structure and pointer. But for some reason it is not working properly. The main problem is that, for-loop would no go as it would. It would be helpful if you could solve this problem
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct Book{
string name;
int release;
};
int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];
//for handler
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;
}

You're not checking if the input succeeded, nor are you clearing the new line left after the extraction into choice:
if ((std::cout << "Book: "),
std::getline(std::cin >> std::ws, Input[i].name) &&
(std::cout << "Release Date: "),
std::getline(std::cin >> std::ws, release_dte))
{
Input[i].release = std::stoi(release_dte);
}
You should also be using std::stoi for C++ strings as shown above.

I could not exactly infer what is the problem you are referring to. But my guess is getline() function inside the for loop is not working properly, I suggest the code before the for loop to be like the following\
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
Your final code should be
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct Book{
string name;
int release;
};
int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//for handler
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;
}
This will work as you intended

Related

expected primary-expression before 'int'- How can I sort out the problem?

I'm creating a database for Customer in C++. The firt void works well but the second one returns me the following error: expected primary-expression before 'int'
Where is teh mistake? How can I figure out it?
I can't understand why I receive this error. I'm a beginner and this is my firt important project.
Many thanks!!!
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <cstdio>
using namespace std;
class DataCustomer{ //initialize a class
public:
DataCustomer(){
count = 0 ;
}
void AddCustomer();
void DisplayAll(int i);
void DeleteFile();
void EditFile();
void quit();
void search();
void searchName();
void searchSurname();
void searchCell();
void searchEmail();
int Menu();
//defining New Customer's details
struct NewCustomer
{
char Name[20];
char Surname[20];
char Birthday[10];
char PhoneNum [15];
char Email[20];
};
NewCustomer entries [10000];
int count;
};
void DataCustomer::AddCustomer()
{
cout<<"Enter a Name: ";
ofstream a_file ("database.txt", ios::app);
cin >> entries[count].Name;
a_file << entries [count].Name<<"\n";
cin.clear();
cin.sync();
cout << "Enter a Surname: ";
cin >> entries[count].Surname;
a_file << entries[count].Surname << "\n";
cin.clear();
cin.sync();
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
a_file << entries[count].Birthday << "\n";
cin.clear();
cin.sync();
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
a_file << entries[count].PhoneNum << "\n";
cin.clear();
cin.sync();
cout << "Enter Email: ";
cin >> entries[count].Email;
a_file << entries[count].Email << "\n";
a_file.close();
++count;
}
void DataCustomer::DisplayAll(int i)
{
system ("cls");
cout<<"Entire Customers' database:"<<endl;
ifstream a_file ( "database.txt" );
a_file>> entries[i].Name;
a_file>> entries[i].Surname;
a_file>> entries[i].Birthday;
a_file>> entries[i].PhoneNum;
a_file>> entries[i].Email;
cout << "Name : " << entries[i].Name << endl;
cout << "Surname: " << entries[i].Surname << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
cout << "Number of Entries : " << count << endl;
for(int i = 0;i < count;++i)
{cout << endl;
DisplayAll(i); }
}
DataCustomer db;
int main ()
{
db.DisplayAll(int i);
return 0;
}

Access the loop result to instance of class for output

Alright, so I have an class-inventory assignment for my C++ class. The thing I'm struggling with right now is the part between the loop and object creation.
string description = "";
int id_number{0};
int quantity_number{0};
double price_value{0};
for (int count{1}; count <= inventory_num; count++)
{
cout << endl;
cout << "Item #" << count++ << endl;
cout << "Enter the id number: ";
cin >> id_number;
cout << "Descriptiom: ";
cin.get();
getline(cin, description);
cout << "Quantity on hand: ";
cin >> quantity_number;
cout << "Unit price: ";
cin >> price_value;
cout << endl;
}
InventoryItem item1(id_number, description, quantity_number, price_value);
InventoryItem item2(id_number, description, quantity_number, price_value);
InventoryItem item3(id_number, description, quantity_number, price_value);
InventoryItem item4(id_number, description, quantity_number, price_value);
item1.display(); cout << endl;
item2.display(); cout << endl;
item3.display(); cout << endl;
item4.display(); cout << endl;
return EXIT_SUCCESS;
}
So the problem is, for example, looping the input for 4 times, but the output only shows the the data from the LAST INPUT OF THE LOOP for ALL OF THE OUTPUT(item1,item2,item3,item4). How do fix this lads?
You overwrite the values in each loop iteration. After the loop the values of the last iteration are stored in your variables. You could fix it with a std::vector
#include "InventoryItem.hpp"
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::getline;
int main() {
string description = "";
int id_number{0};
int quantity_number{0};
double price_value{0};
std::vector<InventoryItem> items;
for (int count{1}; count <= inventory_num; count++)
{
cout << endl;
cout << "Item #" << count++ << endl;
cout << "Enter the id number: ";
cin >> id_number;
cout << "Descriptiom: ";
cin.get();
getline(cin, description);
cout << "Quantity on hand: ";
cin >> quantity_number;
cout << "Unit price: ";
cin >> price_value;
cout << endl;
items.emplace_back(id_number, description, quantity_number, price_value);
}
items[0].display(); cout << endl;
items[1].display(); cout << endl;
items[2].display(); cout << endl;
items[3].display(); cout << endl;
return EXIT_SUCCESS;
}

c++ why is there still input buffer left?

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.

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;
}

Character dispaying

I know this maybe such a wierd question but it stucks me for a couple of days ago. My assignemnt is to display the students' information and update them using STRUCT type. Here is my works:
#include <iostream>
using namespace std;
struct DATE
{
int day;
int month;
int year;
};
struct STUDENT{
char ID[8];
char name[50];
DATE birthday;
char address[100];
float Math;
float English;
float CS;
};
void inputClass(STUDENT* &list, int &n)
{
cout << "Please enter the number of students: ";
cin >> n;
list = new STUDENT[n+1];
for(int i=1; i<=n; i++)
{
cout << "Please enter the info of student " << i << endl;
cout << "ID: ";
cin >> (&list[i]) -> ID; //the same with "list[i].ID"
fflush(stdin);
cout << "Name: ";
cin >> (&list[i]) -> name;
fflush(stdin);
cout << "Date of Birth\n";
cout << "Day: ";
cin >> (&list[i]) -> birthday.day;
fflush(stdin);
cout << "Month: ";
cin >> (&list[i]) -> birthday.month;
fflush(stdin);
cout << "Year: ";
cin >> (&list[i]) -> birthday.year;
fflush(stdin);
cout << "Address: ";
cin >> (&list[i]) -> address;
fflush(stdin);
cout << "Math result: ";
cin >> (&list[i]) -> Math;
fflush(stdin);
cout << "English result: ";
cin >> (&list[i]) -> English;
fflush(stdin);
cout << "CS result: ";
cin >> (&list[i]) -> CS;
fflush(stdin);
cout << "************* Next Student *************\n" ;
}
}
void updateScore(STUDENT* list, int n)
{
cout << "Who do you want to update?" << endl;
cout << "Ordinal Number(s): ";
cin >> n;
//Display outdated results
cout << "Student's Name: " << (&list[n])-> name << endl;
cout << "*********** Current Results ***********" << endl;
cout << "Math: " << (&list[n]) -> Math << endl;
cout << "English: " << (&list[n]) -> English << endl;
cout << "CS: " << (&list[n]) -> CS << endl;
//Update results
cout << "Please update the results" << endl;
cout << "Math result: ";
cin >> (&list[n]) -> Math;
fflush(stdin);
cout << "English result: ";
cin >> (&list[n]) -> English;
fflush(stdin);
cout << "CS result: ";
cin >> (&list[]) -> CS;
fflush(stdin);
}
void main()
{
STUDENT* list;
int n;
inputClass(list, n);
updateScore(list, n);
}
In the "//Display outdated result" section, I used "cout" to print out the Name of the regarding student based on his/her ordinal numbers. However, let's say I want to get the whole name like: "John Smith". What I have got, however, is only "John". Is there a way I can get all of the characters?
Many thanks for your help and sorry for my bad English, I am a student from Vietnam.
Use std::getline from the <string> header, with a std::string variable, instead of >> and raw character array.
The >> reads whitespace-separated words of input.
The raw character array doesn't adjust to the needed length, and you risk Undefined Behavior on buffer overflow.
In passing, many/most programmers find all UPPERCASE to be an eyesore; it hurts the eyes.
Also, all uppercase is by convention (in C and C++) reserved for macro names.
As it's already been answered previously, you should use std::getline (refer to this question).
I'm assuming you're using a IDE, and it usually fixes a lot of things for us, users, but this may turn your code non-compilable in other compilers, so there are some things you should fix to be able to compile your code everywhere:
Always pay attention if you're adding the necessary includes. There's lack of an include statement for stdin and fflush. You should add:
#include <cstdio>
Also, main should return an int, so, it should have been something like
int main(int argc, char* argv[]){ /*Although you can usually omit the parameters*/
// Code
return 0;
}
By the way, just as a side comment, you forgot the subscript at:
cout << "CS result: ";
cin >> (&list[]) -> CS;