Hey man, glad you're enjoying it.
In the future, try and use the code tags. Not just because it makes it easier to read, but also we can run it in Shell here, which is quite helpful! [ code ] [/ code ] (no spaces)
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your first name and age\n";
string first_name;
int age;
cin >> first_name;
cin >> age;
cout << "Hello, " << first_name << " (age " << age << ")\n";
return 0;
}
|
Just glancing over it, it SHOULD work, unless I'm missing something, which is entirely possible. It's possibly a g++ issue.
EDIT: Ran it in Shell, and I got:
1 2 3 4 5
|
Please enter your first name and age
Rehan 26
Hello, Rehan (age 26)
Exit code: 0 (normal program termination)
|
I was reading about "getline" and I really do not understand it. |
getline() doesn't really apply here. Stroustrup actually does discuss that soon after (if I recall correctly), but getline() reads until it receives a newline and ignores other whitespace, whereas string reads until whitespace. In this case, you're reading a string and then an int directly after, so this:
Rehan 26
Will read Rehan into the string, and 26 into the int, because after the 'n' is preceded by a space. Does that make sense? For getline(), if you wanted, you could do something like this:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
int main()
{
cout << "Enter your name: ";
string name;
getline(cin, name);
cout << "Hello, " << name << "!\n";
return 0;
}
|
And you could type in Rehan Anderson Smith, the Greatest Ever and the output would be:
|
Hello, Rehan Anderson Smith, the Greatest Ever!"
|