Jul 21, 2011 at 1:33pm Jul 21, 2011 at 1:33pm UTC
Hi all experts,
I would like to know how come the string variable doesn't store the entire data entered. for example,
cout << "Product name: ";
cin >> expName;
cout << expName;
if i entered "Mobile Bill", the print out will be "Mobile".
Your help will be greatly appreciated.
Thanks!
Jul 21, 2011 at 1:42pm Jul 21, 2011 at 1:42pm UTC
Because operator>> for strings only reads until the next whitespace (so basically, a word).
If you want an entire line, use getline(cin,expName);
Jul 21, 2011 at 2:10pm Jul 21, 2011 at 2:10pm UTC
Thanks Athar! Do you mind enlighten me on this...
cout << "Expense Name: ";
getline(cin, expName);
cout << "Amount: ";
getline(cin, expPrice);
string output = expName + ":" + expPrice;
cout << output;
when i entered "Mobile Bill" for "Expense Name". The data is save into expPrice instead. How do i solve this?
Jul 21, 2011 at 2:13pm Jul 21, 2011 at 2:13pm UTC
That shouldn't happen as long as you don't do anything strange.
Can you provide a compilable example?
Jul 22, 2011 at 10:10am Jul 22, 2011 at 10:10am UTC
#include <cstdlib>
#include <iostream>
using namespace std;
int getMenu(){
//declaring variable
int selOption;
//printing the menu out
cout << "========================" << endl;
cout << "Welcome to PCFM System" << endl;
cout << "========================" << endl;
cout << "[1] Add new expense" << endl;
cout << "[2] Remove expense" << endl;
cout << "[3] Edit cash flow for either income or expenses" << endl;
cout << "[4] Net Cash flow summary report" << endl;
cout << "[0] Quit" << endl;
cout << "Please make your selection: ";
cin >> selOption;
return selOption;
}
int main(int argc, char** argv) {
bool validated;
int selOption;
string expName, expPrice;
validated = login.loginMenu();
if (validated == true)
{
selOption = getMenu();
if (selOption == 1)
{
system("clear");
cout << "Enter Expense: ";
getline(cin, expName);
cout << "Enter Amount: ";
getline(cin, expPrice);
cout << expName + ":" + expPrice << endl;
}
else
cout << "Enter valid option";
}
else
cout << "Login Invalid";
return 0;
}
The codes in bold has been giving me problem. If i entered "Mobile Bills" it will display ":Mobile Bills". The actual output i should get is "Mobile Bills:$100".
Jul 24, 2011 at 6:38pm Jul 24, 2011 at 6:38pm UTC
I have solved this problem already!
Simply use cin.ignore();