How to skip a field without entering value in c++ - c++

In the below code phone number is not mandatory. How can i skip the field? If i press enter it is still waiting for my input. I want to skip the phone number field if necessary. Is that possible in C++.
#include <iostream>
using namespace std;
int main()
{
string id, name, phone, dob;
cout << "Enter id";
cin >> id;
cout << "Enter name";
cin >> name;
cout << "Enter phone number";
cin >> phone;
cout << "Enter date of birth";
cin >> dob;
}

std::string phone_number;
std::getline(std::cin, phone_number);
gets what ever was entered on that line including nothing.

Use getline(cin, name); instead of cin>>name;. It will put a complete line to the variable. If you just press ENTER it will put an empty line.

Related

`cin >> variable` doesn't wait for input

#include <iostream>
#include <string>
#include "Friend.h"
#include "Address.h"
using namespace std;
int main() {
string name = "";
string street = "";
string city = "";
string state = "";
long phone_number = 0000000000;
int zip_code = 00000;
int feet = 0;
int inches = 0;
cout << "What is your friends name: ";
cin >> name;
cout << "What street does he live on: ";
cin >> street;
cout << "What city does he live in: ";
cin >> city;
cout << "What state does he live in: ";
cin >> state;
cout << "What is his 10 digit phone number: ";
cin >> phone_number;
cout << "What is his zip code: ";
cin >> zip_code;
cout << "How tall is he in feet: ";
cin >> feet;
cout << "And how many inches: ";
cin >> inches;
return 0;
}
This is my code. The problem here is: after I enter my phone number, it just doesn't wait for an input any more. It will output the cout << statements that follow automatically and then terminate it self. I am not sure why this happens.
Could someone help me please?
The variable phone_number is of type long, which is the same as long int. This means that you can only enter numbers as input for phone_number.
The best guess why it doesn't work for you is that you enter the phone number as: XXX-XXXXXXX (with the dash). The "-" splits the input, and the numbers after the dash are passed on to the next input variable zip_code.
If you try input for phone number as: 1234567890, then it works fine. If you want to use the dash, then consider changing phone_number to type string.
As an aside, take input for your string-type variables using getline() instead of cin << so that the compiler will continue reading all input until the ENTER key is hit.

cin is skipping a line

Here's a segment of code that I am working on:
std::cout << "Enter title of book: ";
std::string title;
std::getline(std::cin, title);
std::cout << "Enter author's name: ";
std::string author;
std::getline(std::cin, author);
std::cout << "Enter publishing year: ";
int pub;
std::cin >> pub;
std::cout << "Enter number of copies: ";
int copies;
std::cin >> copies;
Here's the output from this section when it is running (added quotes):
"Enter title of book: Enter author's name":
How do I fix this so that I can enter in the title?
I think you have some input before that you don't show us. Assuming you do you can use std::cin.ignore() to ignore any newlines left from std::cin.
std::string myInput;
std::cin >> myInput; // this is some input you never included.
std::cin.ignore(); // this will ignore \n that std::cin >> myInput left if you pressed enter.
std::cout << "Enter title of book: ";
std::string title;
std::getline(std::cin, title);
std::cout << "Enter author's name: ";
Now it should work.
getline is newline delimited. However, reading with something like std::cin leaves the newline in the input stream. As this recommends, when switching from whitespace delimited to newline delimited input, you want to clean all newlines from the input stream by doing a cin.ignore: for example, cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');. (Of course, I am assuming you left out the cin before getline when distilling your code into an MCVE).

String getline(cin,variable) function is skipping some lines of code

My program skips some code when I use the getline(cin,variablehere) function. I don't know whats wrong with the code. See the output below
#include <iostream>
#include <string>
using namespace std;
int main()
{
string getfirstname;
string lastname;
string address;
int contactnumber;
cout << "Enter First name : ";
getline(cin, getfirstname);
cin.ignore();
cout << "Enter Last name : ";
getline(cin, lastname);
cin.ignore();
cout << "Enter Address : ";
getline(cin, address);
cin.ignore();
cout << "Enter Contact number : ";
cin >> contactnumber;
cin.ignore();
CurrentNumberOfContacts += 1;
cout << "Successfully added to contact list!" << endl << endl;
cout << "Would you like to add another contact ? [Y/N] ";
cin >> response;
//more lines of codes below
return 0;
}
I have inputed 'int' as data type because it will contain numbers only
I recommend removing all the cin.ignore() commands.
One of the problems with user input is that the >> operator does not take the RETURN character out of the stream so if you follow it with a getline() the getline() will read the RETURN character instead of what you want to type in.
So I would change all your getline() to this:
// cin >> ws will skip any RETURN characters
// that may be left in the stream
getline(cin >> ws, lastname);
Also remove all of your cin.ignore() commands. They are not doing anything useful when used after a getline() command and if you change your getline() commands as I showed they should not be necessary at all.
So this should work:
int main()
{
string getfirstname;
string lastname;
string address;
char response;
int contactnumber;
int CurrentNumberOfContacts = 0;
cout << "Enter First name : ";
getline(cin >> ws, getfirstname);
cout << "Enter Last name : ";
getline(cin >> ws, lastname);
cout << "Enter Address : ";
getline(cin >> ws, address);
cout << "Enter Contact number : ";
cin >> contactnumber;
CurrentNumberOfContacts += 1;
cout << "Successfully added to contact list!" << endl << endl;
cout << "Would you like to add another contact ? [Y/N] ";
cin >> response;
//more lines of codes below
return 0;
}
Strictly speaking not all of your getline() functions need to employ the cin >> ws trick. I suppose the (incomplete) rules are as follows:
If you use a std::getline() after a >> then use:
std::getline(cin >> ws, line);
Otherwise just use:
std::getline(cin, line);
cin >> and getline do not cooperate very well. They have different strategies for how to deal with whitespace. getline removes the newline character, but cin >> leaves it. This means that after you use cin >> to read something, there will be a newline character left waiting in the input stream for the next getline to "use". Which means it will read an empty line into the string.
2 things. First, you don't really need cin.ignore() in this case as your using
getline().
before
cin >> variable
Second, I don't know why your program doesn't run, but I would suggest using a
getline()
call and see if that works. But I see no reason why your code is not working.
The answer provided by #Galic is quite good but If you want to read a line of characters without discarding the leading spaces you need another solution.
You could do:
char a='\n';
while (a=='\n')
{
cin.get(a);
}
cin.unget();
before doing your first getline. This assumes no trailing space resulting from a previous cin and that your first input line is not empty.

taking first string input and then ignoring the rest

I want the user to enter a string, double and a long, but the thing is after the first time, the string is kind of being ignored and left empty and prompting for the double directly.
here's my code:
#include <iostream>
#include <string>
using namespace std;
int main () {
string name;
double price;
long serial;
cout << "Enter the dvd's name: "; getline(cin, name);
cout << "Enter the dvd's price (in $): "; cin >> price;
cout << "Enter the dvd's serial number: "; cin >> serial;
cout << endl;
cout << "Enter the dvd's name: "; getline(cin, name);
cout << "Enter the dvd's price (in $): "; cin >> price;
cout << "Enter the dvd's serial number: "; cin >> serial;
return 0;
}
as you can see the first time, i can enter a string the second time just sends me directly to the double, and even if i ignored the missing string, and put a double and then a long, it will print name as empty string.
What is wrong with my code?
I generally use istringstream in such cases (as shown below). But a better solution would be to use cin.ignore
#include <sstream>
int main () {
string name,line;
double price;
long serial;
cout << "Enter the dvd's name: "; getline(cin, line);
name = line;
cout << "Enter the dvd's price (in $): ";
getline(cin,line);
istringstream(line)>>price;
cout << "Enter the dvd's serial number: ";
getline(cin,line);
istringstream(line)>>serial;
cout << endl;
return 0;
}
The whitespace (carriage returns or space) after the serial number is not retrieved, and the getline then picks it up.
Edit: As johnathon points out, cin >> ws does not work right in this case (I'm sure I used this like this before, though I can't find an example).
Tested Solution: Instead, adding this after the serial number will get the carriage return (and any other whitespace) out of the stream so that it is ready for the next DVD name.
string dummy;
getline(cin, dummy);

C++ quick issue on getline(cin, string)

Its been a while since i have coded c++ and i have forgot an annoying thing that happens when you gather string input. Basically if this loops back through, say if you use negative numbers then it skips the cin from the employee name line the second go round. I remember having this issue before and having to clear or do something of that sort before or after the string is input. Please help!
PS Also for extra help can anyone help me with a correct loop below. How can i check for a value in the string input to make sure they input a value?
#include <string>
#include <iostream>
#include "employee.h"
using namespace std;
int main(){
string name;
int number;
int hiredate;
do{
cout << "Please enter employee name: ";
getline(cin, name);
cout << "Please enter employee number: ";
cin >> number;
cout << "Please enter hire date: ";
cin >> hiredate;
}while( number <= 0 && hiredate <= 0 && name != "");
cout << name << "\n";
cout << number << "\n";
cout << hiredate << "\n";
system("pause");
return 0;
}
You want to change your loop condition to be whether or not any of the below are not set. The logical AND will only trigger if all three are unset.
do {
...
} while( number <= 0 || hiredate <= 0 || name == "");
Next, use cin.ignore() as prescribed by #vidit to get rid of issues with reading in newline characters.
Lastly, and importantly, your program will run an infinite loop if one enters an alphabetic character for an integer instead of...an integer. To mitigate that, use isdigit(ch) from the <cctype> library.
cout << "Please enter employee number: ";
cin >> number;
if(!isdigit(number)) {
break; // Or handle this issue another way. This gets out of the loop entirely.
}
cin.ignore();
cin leaves a newline character(\n) in the stream, which causes the next cin to consume it. There are many ways of getting around that. This is one way.. using ignore()
cout << "Please enter employee name: ";
getline(cin, name);
cout << "Please enter employee number: ";
cin >> number;
cin.ignore(); //Ignores a newline character
cout << "Please enter hire date: ";
cin >> hiredate;
cin.ignore() //Ignores a newline character