• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

Simple Question

Hello, I am building an application, Main is as follows:

int main(){
string strEmployeeName;
double dblHoursWorked;
double dblPayRate;
cout << strAppName << " v" << intMainVersion
       << "." << intSubVersion
       << ", revision " << intRevision
       << "\n\n";
cout << "Employee Name: ";
cin >> strEmployeeName;
cout << "Hours Worked: ";
cin >> dblHoursWorked;
cout << "Pay Rate: ";
cin >> dblPayRate;
return 0;
}

all of the problem include files have been included, however, after I input the Employee name and hit enter, the program just ends, it does not ask me for the input of Hours Worked or Pay Rate.


Whats wrong?

-Brian
0
BrianGEFF719
Asked:
BrianGEFF719
  • 2
2 Solutions
 
avizitCommented:
tried the following on my computer , linux

int main(){
string strEmployeeName;
double dblHoursWorked;
double dblPayRate;
cout << "Employee Name: ";
cin >> strEmployeeName;
cout << "Hours Worked: ";
cin >> dblHoursWorked;
cout << "Pay Rate: ";
cin >> dblPayRate;
return 0;
}
 
i.e i removed  the cout which referred to strAppName etc
and it worked fine and it asked for name , hours worked and pay rate  just fine

0
 
avizitCommented:
so obviously your code is fine , maybe something else is wrong ..
which platform you are working on ?
0
 
pankajtiwaryCommented:
Just beautifying your code for readability:-

#include <iostream>
#include <string>

using namespace std;

int main(){
      string strEmployeeName;
      double dblHoursWorked;
      double dblPayRate;

      cout << "Employee Name: ";
      // cin >> strEmployeeName;    change this
         getline(cin, strEmployeeName, '\n');    // This will work perfectly fine.

      cout << "Hours Worked: ";
      cin >> dblHoursWorked;

      cout << "Pay Rate: ";
      cin >> dblPayRate;

      return 0;
}

The code is running fine as long as the employee name is one word. You must be having problem when you try to enter something like "firstname lastname". The problem is in C/C++ the space is taken as a string delimiter, so the strEmployeeName only takes the firstname and the lastname is given to succeessive cin.

If you want so that your program can take input muti words names, then use getline(). Change your "cin >> strEmployeeName;" to  getline(cin, strEmployeeName, '\n'); This will read until it finds a newline.

Cheers!!!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now