C++ simple code issue about cout and cin - c++

I have the following code. Everything works fine but quite different. I expect the first three cout << come one after the another, so when the first message is shown in the console, the user enters the value, and then the next cout << shows another message and the user enters the name of the book, and then the third cout << shows the last message and the user enters the year. But it shows the first message for, I enter the value, and then it shows the next two messages together. Why?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
string AuthorName;
string AuthorBook;
string YearPublished;
cout << "Please Enter the Author Name" << endl;
cin >> AuthorName;
cout << "Please enter the Author Book" << endl;
cin >> AuthorBook;
cout << "Please enter the year when the book was published" << endl;
cin >> YearPublished;
cout << setw(15) << "Author Name";
cout << setw(15) << "Prominent Work";
cout << setw(15) << "Year Published";
cout << endl << endl;
cout << setw(15) << AuthorName;
cout << setw(15) << AuthorBook;
cout << setw(15) << YearPublished;
cout << endl << endl;
return 0;
}

You need to use getline() since C++ stops reading your input at the first space in strings using cin.

Related

I am having trouble with using getline

I am having trouble with my code not reading the whole string name.
I have tried using getline(cin, movieName) as well as cin.ignore(), but I can't get it to work properly.
I am taking a beginner's course to this class, but my professor does not answer their emails.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string movieName;
const float adultTicketPrice = 12;
const float childTicketPrice = 6;
const float percentTheaterKeeps = .20;
int adultTicketsSold, childTicketsSold;
float grossProfit, netProfit, amountPaidToDistributor;
getline(cin, movieName);
cout << fixed << showpoint << setprecision(2);
cout << "What movie played tonight?\t ";
cin >> movieName;
cout << "How many adult tickets were sold? ";
cin >> adultTicketsSold;
cout << "How many child tickets were sold? ";
cin >> childTicketsSold;
grossProfit = adultTicketPrice * adultTicketsSold + childTicketPrice * childTicketsSold;
netProfit = grossProfit * percentTheaterKeeps;
amountPaidToDistributor = grossProfit - netProfit;
cout << setw(10) << left << "Movie Name";
cout << setw(23) << right << movieName << endl;
cout << setw(10) << left << "Adult Tickets Sold";
cout << setw(16) << right << adultTicketsSold << endl;
cout << setw(10) << left << "Child tickets sold";
cout << setw(16) << right << childTicketsSold << endl;
cout << setw(10) << left << "Gross Box Office Profit";
cout << setw(11) << right << grossProfit << endl;
cout << setw(10) << left << "Net Box Office Profit";
cout << setw(13) << right << netProfit << endl;
cout << setw(10) << left << "Amount Paid to distributor";
cout << setw(8) << right << amountPaidToDistributor << endl << endl;
return 0;
}
You need to use std::getline(std::cin, movieName) when you want to get input for movieName.
Presumably you're seeing a blank line when you start your program, and pressing enter. This sets movieName to '\n'. Remove that line, and switch std::cin >> movieName; with std::getline(std::cin, movieName). (Remove the std::s if you're using a using declaration)

Need help on getting into a function in C++

Here is the sample of my code:
//Function Declarations
void askChampSearch(string&, string&);
void displayChampDetail(string);
int main()
{
string searchedChamp;
string aboutUser;
cout << "**********YOU'RE GOING TO WANT TO MAKE YOUR PROMPT FULL SCREEN**********" << endl;
cout << "Welcome to my LEAGUE OF LEGENDS info guide!" << endl;
cout << "You can search any champion in League of Legends, and all" << endl;
cout << "of that champions information will be displayed.The information" << endl;
cout << "that will be displayed is: Abilites, Champion Lore, About The Campion, Best Build, and the Champions Wiki Page!" << endl;
cout << endl;
askChampSearch(aboutUser, searchedChamp);
displayChampDetail(searchedChamp);
return 0;
}
//Function Definitions
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
cin >> UserName;
cout << "Hi " << UserName << ", nice to meet you!" << endl;
cout << endl;
cout << "What League of Legends champion would you like to search? ";
cin >> searchedChamp;
cout << "The champion that you have searched for was " << searchedChamp << "!";
}
void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
cout << "Ahri is a nine-tailed fox who is a whore" << endl;
cout << "If Ahri hits you with a charm, you are fucked" << endl;
}
}
What I am having problems with is after my program leaves the first void:
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
cin >> UserName;
cout << "Hi " << UserName << ", nice to meet you!" << endl;
cout << endl;
cout << "What League of Legends champion would you like to search? ";
cin >> searchedChamp;
cout << "The champion that you have searched for was " << searchedChamp << "!";
}
It won't enter into the next one! For example. If the user types the Name Ahri it should display what I have done, but it says I need to define Ahri. How do I define Ahri within the second Void. Here is the code for my second Void:
void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
cout << "Ahri is a nine-tailed fox" << endl;
cout << "If Ahri hits you with a charm, you are dead" << endl;
}
}
What I am trying to do is, if the user types the name Ahri, it the information that I have provided.
The error code that I am getting is identifier "Ahri" is undefined.
searchedChamp == "Ahri"
It is a string. Other wise compiler tries to find a variable with name "Ahri"and it doesn't find it so it asks you to define it.

Code not allowing user input in strings after first string

I have looked around and can't seem to find an answer to this. I am new to C++ and am attempting to write a program for a class that asks the user for the first and last names of 4 students and their ages. The program will then display the input names and ages and also display the average of the ages.
The issue I am having is that the program allows for input of the first name and age but then skips over the remaining three name input fields and only allows for the remaining three ages to be input.
I apologize if this ends up being a dumb question but I really am at a loss. Any help will be greatly appreciated.
Here is the code I have thus far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string studentname1;
cout << "Please enter the first student's full name:" << endl;
getline(cin, studentname1);
int age1;
cout << "Please enter the first student's age:" << endl;
cin >> age1;
string studentname2;
cout << "Please enter the second student's full name:" << endl;
getline(cin, studentname2);
int age2;
cout << "Please enter the second student's age:" << endl;
cin >> age2;
string studentname3;
cout << "Please enter the third student's full name:" << endl;
getline(cin, studentname2);
int age3;
cout << "Please enter the third student's age:" << endl;
cin >> age3;
string studentname4;
cout << "Please enter the fourth student's full name:" << endl;
getline(cin, studentname2);
int age4;
cout << "Please enter the fourth student's age:" << endl;
cin >> age4;
cout << "Hello from our group." << endl;
cout << "NAME AGE" << endl;
cout << studentname1 << " " << age1 << endl;
cout << studentname2 << " " << age2 << endl;
cout << studentname3 << " " << age3 << endl;
cout << studentname4 << " " << age4 << endl;
cout << "The average of all our ages is: " << (age1 + age2 + age3 + age4) / 4.00 << endl;
return 0;
}
Since the age variables are int, the cin >> age1; will leave the newline character in the input stream. When next you call getline(), you will get the remainder of that line - which is empty, and so on.
Also, you have a copy-paste bug in your code. getline(cint, studentname2); is run for students 2, 3 and 4.
You can either solve the problem by using getline() for all input:
string agestring;
getline(cin, agestring)
stringstream(agestring) >> age1;
or clear cin when you're done reading the age:
cin >> age1;
cin.ignore();

I am trying to use a do while loop to repeat a certain portion of my program and it refuses to execute properly

Okay so as the title said its refusing to execute the stuff right under the "do" function even though as far as i can tell all the parameters for a repeat have been fulfilled. So far what i get when i run the program is something along the lines of...
"Would you like to search another name?
Please enter Y for yes and n for no:"
looping over and over when i press y
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, sID, sClass, sSearch, cQuestion;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << endl;
}
cout << "\n";
// Search function
do
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
} while (cQuestion == "Y" || cQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
Edit:
Posted whole program, please excuse any grammatical mistakes, I'm just trying to get the program down before i go in there and make it pretty.
The tail of your loop does this:
cout << "Please enter Y for Yes and N for No:" << endl << endl;
cin >> cQuestion;
which will consume your string if you entered one, but leave the trailing newline in the input stream. Thus when you return to the top of the loop after entering Y or y, and do this:
cout << "Please Enter a name to be searched:" << endl;
getline(cin, sSearch);
the getline will extract an empty line.
How to consume the unread newline from the input stream is up to you. You will likely just end up using .ignore() as you did prior in your program. Or use getline to consume cQuestion. You have options. Pick one that works.
And as a side note, I would strongly advise you check your stream operations for success before assuming they "just worked". That is a hard, but necessary, habit to break. Something like this:
do
{
cout << "Please Enter a name to be searched:" << endl;
if (!getline(cin, sSearch))
break;
if (binary_search(vName.begin(), vName.end(), sSearch))
{
cout << sSearch << " was found." << endl << endl;
}
else
{
cout << sSearch << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
} while (getline(cin,cQuestion) && (cQuestion == "Y" || cQuestion == "y"));
If cQuestion is a char array then you need to use strcmp or stricmp to compare it with another string i.e. "Y" and "y" in this case. If cQuestion is a single char then you need to compare with 'Y' and 'y' (i.e. with a single quote)
Strings in C++ are not first class types therefore they do not have some of the string operation that exist for other basic types like ints and floats. You do have std::string as part of the standard C++ library which almost fulfills the void.
If you just change the type of cQuestion to std::string your code should work but if you want to stick with chars then you will need to change the quote style.

Why getline does not work in a switch, and cin does not take the data appropriately?

I need to take in the make model and years of the car the particular product fits. The program is going to write a file with text in it that will be an outline of the html. I need with the crucial information inserted into the correct spots to quickly be able to add products to our web page. When I use a switch statement or if statements to separate the categories of the products, the input gets messed up and does not let me answer one of the questions. I can't just use cin because I need to take dates that look like "2008 - 2009 - 2010 - 2011".
Here is what I've got so far! This one is just regular cin, I have tried getline you could quickly c I started yesterday and I'm pretty new so forgive me if this is an easy fix, but I cant find anything.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void proinfo();
int main()
{
//Sytem Information
system("TITLE This is a Beta of My Product Information Template Version 0.0.2");
//I'm using this as a welcome screen to inform users of new improvements on patches and other pertinent information to the users
cout << "Welcome To My Product Information Template Maker!!! \n It Is Still In Development" << endl;
cout << "\n\nworking features are:" << endl << "\t-None\n" << endl;
system("PAUSE");
system("CLS");
proinfo();
}
void proinfo()
{
//Declare Variables here
int loop(1), protype;
char make[256], model[256], year[256];
string getinput;
while(loop==1)
{
//This is the first menu the user sees where they have to choose what type
//of products users will be adding
system("CLS");
cout << "Welcome to My Product Information Template Version 0.0.0" << endl;
cout << "Please select the number of the product" << endl;
cout << "type you will be ading!\n" << endl;
cout << "1.Fe - Fe2 Moldings" << endl;
cout << "2.CF - CF2 Moldings" << endl;
cout << "What would you like to do? ";
cin >> protype;
if(protype==1)
{
//FE - FE2 Molding
system("cls");
cout << "You have selected" << endl;
cout << "Fe - Fe2 Moldings\n" << endl;
cout << "Please Enter the Make of the molding" << endl;
cin >> make;
cout << "Please Enter the Model of the molding" << endl;
cin >> model;
cout << "Please Enter the Years this molding fits" << endl;
cin >> year;
cout << "You have just created a template for a(n)" << year << " " << make << " " << model << endl;
cout << "Check My Documents For a file called Fe-Fe2template.txt" << endl;
//Asks to quit or restart
cout << "Would you like to make another tempalte?" << endl;
cin >> getinput;
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
system("PAUSE");
}
if(protype==2)
{
//CF - CF2 Molding
system("cls");
//Asks to quit or restart
cout << "Would you like to make another tempalte?" << endl;
cin >> getinput;
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
system("PAUSE");
//End of Protype Switch Statement
}
//End of while loop
}
//End of Proinfo()
}
Change year[256] to string year;
Change cin >> year; to getline(cin, year);
Add the line cin.ignore(); before the getline.
Your main problem is that the stream operator >> leaves the newline in the stream so when you try to use getline it reads an empty line. ignore() will chew up the newline and let you read the string you expect.
So this should get you on your way.
cin.ignore();
cout << "Please Enter the Years this molding fits" << endl;
getline(cin, year);
You have some other small problems but you'll figure them out. The worst is forgetting to terminate the loop.
if(getinput=="yes")
{
cout << "Great, Lets keep working!" << endl;
//End of If statement
}
else
{
loop = 0;
continue;
}