#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.
Related
I read some answers regarding how to fix it but I'm trying to also understand the concept behind it (i.e. why does the first getline work fine).
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main(){
string ticker = "";
string date = "";
int pprice;
int sprice;
cout << "Enter the stock ticker =>" << endl;
getline(cin, ticker);
cout << "Enter the purchase price =>" << endl;
cin >> pprice;
IT WORKS FINE UNTIL IT GETS TO HERE:
cout << "Enter the sell date =>" << endl;
getline(cin, date);
cout << "Enter the sell price =>" << endl;
cin >> sprice;
cout << ticker << endl;
return 0;
}
/*OUTPUT:
Enter the stock ticker =>
XYZ
Enter the purchase price =>
12.34
Enter the sell date =>
Enter the sell price =>
12.34
XYZ
*/
You're probably not using cin.ignore() in the correct place. It should be used after std::cin and before getline().
For Example:
int x;
string y;
cin >> x;
cin.ignore(INT_MAX);
getline(cin, y);
The idea is to remove the carriage returns, newlines etc that cin leaves behind on the stream which cause getline() to immediate take and return.
int x=0;
string fullname = "";
float salary;
float payincrease;
float newsal;
float monthlysal;
float retroactive;
while(x<3){
cout << "\n What is your full name?";
cin >> fullname;
cout << "\n What is your current salary? \t";
cin >> salary;
cout << "\n What is your pay increase? \t";
cin >> payincrease;
newsal = (salary*payincrease)+salary;
monthlysal = newsal/12.00;
retroactive = (monthlysal*6)-(salary/2);
cout << "\n" << fullname << "'s SALARY INFORMATION";
cout << "\n New Salary \t Monthly Salary \t Retroactive Pay";
cout << "\n \t" << newsal << "\t" << monthlysal << "\t" << retroactive;
x++;
}
My loop doesn't seem to stop for every time cin is asked, and instead instantly executes the loop 3 times on its own. How do I get it to stop when input is asked?
If the input stream isn't empty when you call cin, then cin uses the data already in the buffer instead of waiting for more from the user. You're using the extraction operator, so when cin is sending values to your variables, it skips leading whitespace in the buffer and stops on the next whitespace.
Put a breakpoint on this line:
cout << "\n What is your current salary? \t";
Run the program, and enter Bob Smith. When you hit the break point, hover your cursor over your string fullname. You'll see it stores only "Bob" not "Bob Smith". "Bob Smith" got put into the buffer, but when you use cin with the extraction operator, it skips any leading whitespace, puts the next value it finds into your variable, then stops on the next whitespace. To demonstrate this, try running this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1,str2;
cin >> str1;
cin >> str2;
cout << str1 << " " << str2 << "\n\n";
return 0;
}
If you type in "Bob Smith", it will take your input only one time, even though you call cin twice. However, you'll see that both "Bob" and "Smith" got captured in the strings str1 and str2.
Therefore, you can conclude that cin stops populating your string fullname when it gets to the space between Bob and Smith. On your next call to cin, the buffer still contains "Smith", so instead of taking more input from the user, it attempts to fill your variable salary with "Smith". Obviously this isn't want you want to do. You can call flush and ignore on cin to wipe out the buffer before every time you use cin, or instead you could fix your logic and use getline to take in the full name, including spaces.
To fix your problem, all you need to do is use getline instead of cin >>, so replace this line:
cin >> fullname;
with this:
getline(cin,fullname,'\n');
Secondly, you're using a while loop to execute a set of actions a specific number of times. That's typically something you'd use a for loop for.
As an aside, you could also write tiny input validation loops that can help you debug or otherwise avoid attempting to put invalid input into your variables (such as "Smith" into a float). Something like this could work:
for(;;)
{
if(cin >> salary)
break;
cin.clear();
cin.ignore(INT_MAX,'\n');
}
Note that cin returns a value, so you can use it in an if statement. If it gets valid input, it will return true. If not, it will return false. To make it more explicit, you could also just use a normal call to cin without the if statement, and then check if cin.good(), which amounts to basically the same net effect. If you're not using Visual Studio and get an error about INT_MAX, you might need to #include limits.h to resolve it.
That occurs if you input a char where an int is expected.
Use cin.clear(); and cin.ignore(numeric_limits<streamsize>::max(), '\n'); to limit an input to int's only.
Other than that, it won't skip if the correct data type is put in.
#include <string>
#include <iostream>
#include <limits>
using namespace std ;
int main(void)
{
int x=0;
string fullname = "";
float salary;
float payincrease;
float newsal;
float monthlysal;
float retroactive;
while(x<3)
{
cout << "\n What is your full name?";
cin >> fullname;
cin.ignore( 1000, '\n' );
cout << "\n What is your current salary? \t";
cin >> salary;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "\n What is your pay increase? \t";
cin >> payincrease;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
newsal = (salary*payincrease)+salary;
monthlysal = newsal/12.00;
retroactive = (monthlysal*6)-(salary/2);
cout << "\n" << fullname << "'s SALARY INFORMATION";
cout << "\n New Salary \t Monthly Salary \t Retroactive Pay";
cout << "\n \t" << newsal << "\t" << monthlysal << "\t" << retroactive;
x++;
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
Check your variable types, I noticed mine accepting a digit instead of a character, had the same problem (not stopping, loop just kept going on).
> std::cin >> this->controls.button
> DETOX_NUMBER button; // (int)
Change to:
> char button;
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);
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
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.