I am trying to learn C++, anyway I am on if statements.
I coded a program that ask a two user their full name and ages (fictional users), it ask user1 its name and age and user2 the same, but somehow asking the user2's name gets skipped and end up asking the user2's age
why ?
here is my code :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string usernameone;
string usernametwo;
int age1;
int age2;
//ask the users their name and age
cout << "Hi may I know your full name ? : ";
getline ( cin, usernameone, '\n');
cout << "\nHello " << usernameone << " May I know now whats your age ? : ";
cin >> age1;
cout << "Ok thanks for the information, now may I talk to the other user ? thanks.\n\n";
cout << "Hello may I know your full name ? : ";
getline ( cin, usernametwo, '\n');
cout << "\nHello " << usernametwo << " May I know now whats your age ? : ";
cin >> age1;
if(age1 < age2)
{
cout << "looks like " << usernameone << " is older than " << usernametwo;
}
else
{
cout << "ok " << usernametwo << " is older than " << usernameone;
}
if(age2 && age1 >= 100)
{
cout << "your both lying your age can't be 100 and above";
}
cin.ignore();
cin.get();
return 0;
}
cin >> age1;
cout << "Ok thanks for the information, now may
I talk to the other user ? thanks.\n\n";
cout << "Hello may I know your full name ? : ";
leaves '\n' in input stream and you are reading it in the next read
getline ( cin, usernametwo, '\n');
You can ignore this character with:
cin >> age1;
cout << "Ok thanks for the information, now may
I talk to the other user ? thanks.\n\n";
cout << "Hello may I know your full name ? : ";
cin.ignore();
getline ( cin, usernametwo, '\n');
Related
Hi i dont know how to allow the user to choose one of the choices i provided in my code and if they picked a choice that was not given then i want the program to return to the last point.
This is my code
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Welcoming message with date//
cout << "Welcome to FILM Screen Cinema" << endl;
cout << endl;
cout << "ENTER STAFF/OPERATOR'S NAME: ";
string name;
cin >> name;
cout << endl;
cout << "ENTER DATE:";
string date;
cin >> date;
cout << endl;
cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:" << endl;
cout << "[1] Deadpool" << endl << "[2] Goosebumps" <<endl;
string input;
cin >> input;
}
Where it says choose a movie, i want the user to type either 1 or 2 for the choices but if they type any other number then it should say invalid and allow them to type 1 or 2 again. Thank you in advance.
I suspect you want each of the std::cin >> XXX calls to actually query the user for input. That is currently not the case, for example when the user types "John Smith" as the name of the operator, name will be set to "John", and the following std::cin >> date reuses the remaining part "Smith" instead of asking for input again.
To fix this, you can use std::getline.
The first part of your code should thus be replaced by
std::cout << '\n';
std::cout << "ENTER STAFF/OPERATOR'S NAME: ";
std::string name;
std::getline(std::cin, name);
std::cout << '\n';
std::cout << "ENTER DATE:";
std::string date;
std::getline(std::cin, date);
std::cout << '\n';
The same is true for the part where you validate the input. Now you only need to add a while-loop to keep asking the user for new input if the previous one was invalid.
std::cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:\n";
std::cout << "[1] Deadpool\n"
<< "[2] Goosebumps\n";
std::string input;
std::getline(std::cin, input);
while(input != "1" && input != "2") {
std::cout << "Invalid!\n\n";
std::cout << "CHOOSE A MOVIE THAT IS SCREENING TODAY:\n";
std::cout << "[1] Deadpool\n"
<< "[2] Goosebumps\n";
std::getline(std::cin, input);
}
if (input == "1") {
// do something
} else if (input == "2") {
// do something else
}
Btw, please consider reading “\n” or '\n' or std::endl to std::cout? and Why is “using namespace std” considered bad practice?
How do i do that without switching the sequence of asking the questions in my program? I would like to get their age, before asking about the course. However, once the age is keyed in, the program automatically proceeds to print the while/if statement.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hi\n"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
cout << "\nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
cout << "What course are you picking up in university ? ";
getline(cin, course);
//If number entered is smaller than 0, print the following message
while (age < 0 ) {
cout << "\nYou can't be younger than 0 years old.";
cout << "\nPlease try again";
cout << "\n\nHow old are you ? ";
cin >> age;
}
//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "\nYou are such a blessed person !\n\n";
}
//If number entered is between 1 and 99, print the following message
if (age > 1 && age < 99) {
cout << "Your name is " << name << " ,and you are " << age << " years old.";
cout << "\n You are planning on taking " << course << " in university.";
}
return 0;
}
If getline() is used after cin >>, the getline() sees this newline character as leading whitespace, and it just stops reading any further.
Solution:
Call cin.ignore() before calling getline()
Or
Make a dummy call getline() to consume the trailing newline character from the cin>>
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hi\n"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
while(true) {
cout << "\nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
if(age>=0)
break;
cout << "\nYou can't be younger than 0 years old.\nPlease try again.";
}
cout << "What course are you picking up in university ? ";
getline(cin, course);
//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "\nYou are such a blessed person !\n\n";
}
//If number entered is between 1 and 99, print the following message
if (age > 1 && age < 99) {
cout << "Your name is " << name << " ,and you are " << age << " years old.";
cout << "\n You are planning on taking " << course << " in university.";
}
return 0;
}
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');
I am having some issues with my simple code of creating a dvd & software list to import into a csv file.
I have the output working fine but for some reason my program is skipping my first part of the code. If I take out the IF statement, that bit of code works so I am not understanding why.
my output looks like this:
Would you like to add new media? Enter M for Movie or S for software: m
Enter the name of the Movie (20 Chararters or less)Name: Enter a rating for
your movie 1-5:
I am not getting any errors in my compiler (Visual Studio 2013) and it does not allow me to input a name and skips right to rating.
Any explanations or suggestions would be appreciated as I want to fix this before I move on to adding more.
here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
string typeM = "movie";
string typeS = "software";
char answer, mediainput;
int rating = 0;
string dir, type;
string moviename,softname;
do
{
cout << "Would you like to add new media? Enter M for Movie or S for software: ";
cin >> mediainput;
cout << endl;
if (mediainput == 'm' || mediainput == 'M')
{
cout << "Enter the name of the Movie (20 Chararters or less) \n Name: ";
getline(cin, moviename);
cout << endl;
cout << "Enter a rating for your movie " << moviename << " 1-5 ";
cin >> rating;
if (rating < 1 || rating > 5)
{
cout << "You must enter a number from 1 to 5. Enter a number rating: ";
cin >> rating;
cout << endl;
}
ofstream outdata("DVD_Software_inventory.csv", ios_base::app);
outdata << moviename << "," << typeM << "," << rating << "," << endl;
outdata.close();
}
if (mediainput == 's' || mediainput == 'S')
{
cout << "Enter the name of the software (20 Chararters or less) \n Software name: " << endl;
getline(cin, softname);
cout << "Enter the directory it is in \n Directory: ";
cin >> dir;
ofstream outdata("DVD_Software_inventory.csv", ios_base::app);
outdata << softname << "," << typeS << ",," << dir << "," << endl;
outdata.close();
}
cout << "\n\nWould you like to add more? Y/N ";
cin >> answer;
cout << endl;
if (answer == 'N' || answer == 'n')
{
cout << "** End of Program **" << endl;
break;
}
} while (answer == 'Y' || answer == 'y');
system("pause");
return(0);
}
The problem is that while your cin >> statement ignores "\n" (the newline character), the character is still in cin's buffer. getline(), however,
does not ignore the "\n" character.
The solution, therefore, is to explicitly tell cin to ignore the "\n" character:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(cin, moviename);
(credit to http://www.cplusplus.com/forum/beginner/24470/)
I have a simple program to read and echoed the user's input and calculate the total amount. I'm having trouble with arrays. I want to know how to use an array to read and print each product name and the cost and the find grand total upon checkout. Should I also use functions?
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
const int MAX_CHAR = 100;
void pause();
int main()
{
char productName[MAX_CHAR];
double price;
char reply;
double total = 0;
cout << fixed << showpoint << setprecision(2);
cout << "Welcome to your shopping calculator!" << endl;
do {
cout << "Enter the product name: ";
cin.get(productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
cout << "Enter the amount: $";
cin >> price;
while (!cin) {
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid amount. Please enter the amount: $";
cin >> price;
}
cin.ignore(100, '\n');
cout << "The product name is" << " " << productName << " "
<< " and it costs" << " " << "$" << price << endl;
total += price;
cout << "The total amount is " << " " << total << endl; //program needs to keep a running total
cout << "Would you like to continue shopping? (y/n): ";
cin >> reply;
cin.ignore(100, '\n');
} while ( reply == 'Y' || reply == 'y'); //the program will continue until the user wants to checkout
pause();
return 0;
}
void pause()
{
char ch;
cout << "Press q followed by Enter key to continue....." << endl;
cin >> ch;
}
Thanks for the help!
You need to map the product name to the cost using std::map so that you can print the respective pairs afterwards. As for the grand total, that's stored in the variable total so printing it is trivial.
To do this, you will need to include the <map> header, as the Standard Library class std::map is defined there. Moreover, I've also included some changes to your code that should be considered. In particular, using std::string and using std::numeric_limits<...>::max() to return the constant.
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string productName;
double price;
char reply;
double total = 0;
std::map<std::string, double> productToPrice;
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << "Welcome to your shopping calculator!" << std::endl;
while ((std::cin >> reply) && (reply == 'y' || reply == 'Y'))
{
cout << "Enter the product name: ";
std::cin >> productName;
cout << "Enter the amount: $";
while (!(cin >> price))
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid amount. Please enter the amount: $";
}
total += price;
productToPrice.insert(std::make_pair(productName, price));
cout << "Would you like to continue shopping? (y/n): ";
}
...
}
Note the changes I made. Please use them.
To print you simply do:
typedef std::map<std::string, double>::const_iterator iter_type;
for (iter_type beg(productToPrice.begin()),
end(productToPrice.end()); beg != end; ++beg)
{
std::cout << beg.first << " -- " << beg.second << std::endl;
}
std::cout << "\nThe total price is: " << total;
You are definitely on the right track. I think you are mixing I/O conventions in C and C++ which is causing a lot of your issues. It would be very helpful if you could elaborate on what exactly your issues are.
Carpetfizz is correct in that since you don't know the number of items at compile time, you will need to use a dynamic array with std::vector. You can learn about vectors here.
In addition, C++ has a very useful string data type that you can include with #include <string>. Using this, as well as a junk string such as string junk;, you can avoid using cin.ignore(...) and get cleaner I/O by using getline(cin, junk).
I strongly recommend doing this because creating a vector of C-strings or C-style strings is a pain, because C-style strings are actually arrays of characters, so you'd have to use std::vector<std::vector<char> > products.