Hi there,
I'm learning C++ from Cay Horstmann's "Big C++", and I stumbled upon the following code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter your full name (first middle last) ";
string first;
string middle;
string last;
cin >> first;
cin >> middle;
cin >> last;
string initials = first.substr(0,1) + middle.substr(0,1) + last.substr(0,1);
cout << "Your initials are " << initials << "\n";
return 0;
}
If I begin middle name with one or more white-spaces, the output does not change. Is this because the .substr begins count only with the first non-whitespace character? For example, if we have the name John David Smith, and I enter,
John
(blank spaces) David
Smith
the output is JDS regardless of whether I type David with or without space before it. This puzzles me. I know that space characters count between two or more words in a string (Hello, World!\n consists of 14 characters total, since the space between the comma and the W is counted). But if I enter a string that begins with a white-space, and I ask .substr to begin count from character 0, does it disregard the space and jump to the first letter?
Any clarification would be greatly appreciated. Thank you!
cin >> str;
When you read in a string like this it will read the first word and ignore whitespaces. So in you example middle will get the value "David" (without spaces).