Ask user for specified amount of characters? - c++

I am new to C++ and I want to prompt the user to enter 10 characters exactly, anything more will just be ignored for example:
Please enter 10 characters:
123412341234
You entered: 1234123412
//and the 34 will be ignored because they entered more than 10
I got to here now:
string userInput;
cout << "Please enter 10 characters!\n";
cin >> userInput;
cout << "You entered: "<< userInput << endl;
Thank you everyone. Hope I am as accurate as I can be.

Just ask the user to enter a string and then take the substring of that
std::string userInput;
std::cout << "Please enter 10 characters: ";
std::cin >> userInput;
if(userInput.length() > 10)
{
userInput = userInput.substr(0, 10);
}
std::cout << "You entered: " << userInput << std::endl;

Related

How do I get the program to request for input for the string "course" before they print out the while/if statement

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

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

Won't let me read in user input in after IF statement (homework)

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/)

Why is my If/Else statment block not executing completely?

I'm doing a simple project for my CS class. The goal is to have a person input the amount of each fruit (apples, bananas, oranges) they are purchasing, and the program calculates the total and presents an invoice at the end. My Professor wants us to also include an input check, to verify that the input is a number between 0 and 100. to do this, I have this section of code.
string name;
int apples, oranges, bananas;
int FRUIT_MAX = 100;
int FRUIT_MIN = 0;
float appleCost, orangeCost, bananaCost,
subTotal, tax, total;
cout << "Welcome to Bob's Fruits, what is your name..." << endl;
getline(cin, name);
cout << "How many apples would you like" << endl;
cin >> apples;
cout << endl;
//checking if user entered a number for apples
if (apples >= FRUIT_MIN && apples <= FRUIT_MAX)
{
cout << "Thanks" << endl;
}
else //makes the user retype entry if invalid
{
cout << "Please input a number thats 0 or greater than 0. " << endl;
cin >> apples;
cout << endl;
}
cout << "How many oranges would you like" << endl;
cin >> oranges;
if (oranges >= FRUIT_MIN && oranges <= FRUIT_MAX) //checking to see if number is good
cout << "Thanks" << endl;
else //makes the user retype entry if invalid
{
cout << "Please input a number thats 0 or greater than 0." << endl;
cin >> oranges;
cout << endl;
}
cout << "How many bananas would you like" << endl;
cin >> bananas;
if (bananas >= FRUIT_MIN && bananas <= FRUIT_MAX)
cout << "Thanks";
else
{
cout << "Please input a number thats 0 or greater than 0.";
cin >> bananas;
cout << endl;
}
When I enter a value between 0-100, I receive the proper "thanks" output and then it moves on to the next question. When I enter a number outside of 0-100, the else statement triggers sucsessfully, and the program asks for a number between 0-11.
The problem is when a letter is input. If a letter is input, the program skips through every remaining line, ignoring any additional cin commands, and displays the formatted invoice with all negative numbers. Any ideas why this is happening?
When cin gets an invalid value, it sets a failbit.
int n;
cin >> n;
if(!cin)
{
//not a number, input again!
}
You need to use cin.ignore() so that the input will be 'reset' and request the input again.
you can change the cin part into
while (!(cin>>apples)) {
cout<<"Type Error"<<endl;
cin.clear();
cin.sync();
}
The Problem ist that you do not check for proper type of your input.
Your apples variable is an Int. So as long as a user enters an Int everything will be fine.
But what happens if he or she enters a Char ?
The answer is as one of the guys before me mentioned is that the cin operation will fail.
What can you do to prevent or better to say handle this situation:
#include<iostream>
using namespace std;
int main(int argc , char** argv) {
int apples = 0; //Its always good to initialise a var with a value
cout << "Please enter a number: " << endl;
cin >> apples;
if(!cin) {
cout << "Not a number!" << endl;
// Handle the error
}
else {
cout << "A number was entered" << endl;
}
return 0;
}
Instead of checking for !cin you can also use cin.fail() which will be true if the last cin operation failed.
If you want to read more about cin or inputstreams in generell I would advise you to take a look at the C++ reference.

Code to get user input not executing/skipping in C++

In the below code, I'm running into an error when I try to get the user to input their name. My program just skips it over and goes right over to making the function calls without allowing the user to enter their name. Despite the error, my program is compiling. I'm not sure what's going wrong as I wrote that part based off other examples I found on here. Any suggestions?
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
char showMenu();
void getLottoPicks(int[]);
void genWinNums(int[]);
bool noDuplicates(int[]);
const int SIZE = 7;
int main()
{
int userTicket[SIZE] = {0};
int winningNums[SIZE] = {0};
char choice;
string name;
srand(time(NULL));
do
{
choice = showMenu();
if (choice == '1')
{
cout << "Please enter your name: " << endl;
getline(cin, name);
getLottoPicks(userTicket);
genWinNums(winningNums);
for (int i = 0; i < SIZE; i++)
cout << winningNums[i];
}
} while (choice != 'Q' && choice != 'q');
system("PAUSE");
return 0;
}
Added the code for showMenu:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
return choice;
}
And getLottoPicks (this part is very wrong and I'm still working on it):
void getLottoPicks(int numbers[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40: " << endl;
for (int i = 0; i < SIZE; i++)
{
cout << "Selection #" << i + 1 << endl;
cin >> numbers[i];
if (numbers[i] < 1 || numbers[i] > 40)
{
cout << "Please choose a number between 1 and 40: " << endl;
cin >> numbers[i];
}
if (noDuplicates(numbers) == false)
{
do
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> numbers[i];
noDuplicates(numbers);
} while (noDuplicates(numbers) == false);
}
}
}
After doing cin >> choice; inside char showMenu(), if a user inputs 1[ENTER], the char consumes 1 character from cin, and the newline stays inside the stream. Then, when the program gets to getline(cin, name);, it notices that there's still something inside cin, and reads it. It's a newline character, so getline gets it and returns. That's why the program is behaving the way it is.
In order to fix it - add cin.ignore(); inside char showMenu(), right after you read the input. cin.ignore() ignores the next character - in our case, the newline char.
And a word of advice - try not to mix getline with operator >>. They work in a slightly different way, and can get you into trouble! Or, at least remember to always ignore() after you get anything from std::cin. It may save you a lot of work.
This fixes the code:
char showMenu()
{
char choice;
cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
cin.ignore();
return choice;
}
from looking at code showMenu function has problem. and it's not returning asccii equivalent of '1' that is: 31 integer. try printing value returned by showmenu. you will get that
UPDATE:
It is because cin in delimited by ' '(whitespace) and getline by '\n' character, so when enter name and press enter cin in showmenu will consume whole string except '\n' from istream and that is read by getline. to see this when it ask for choice enter string like 1 myname (1 whitespace myname)and press ENTER will display name. now cin will read 1 in choice and myname in name by getline.