Mar 23, 2018 at 12:16am UTC
CODE 1
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name="Bruce Wayne";
string letters;
cout << "Please enter your full name: ";
cout << endl;
for (int j=0; j<=name.length(); j++)
{
letters = name.substr(j,1);
cout << letters;
}
cout << endl;
return 0;
}
OUTPUT: "Bruce Wayne"
CODE 2
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
string letters;
cout << "Please enter your full name: ";
cin >> name;
cout << endl;
for (int j=0; j<=name.length(); j++)
{
letters = name.substr(j,1);
cout << letters;
}
cout << endl;
return 0;
}
INPUT: "Bruce Wayne"
OUTPUT: "Bruce"
The substring does not seem to be reading the space in the second type of code, please let me know why this could be, thank you in advance.
Mar 23, 2018 at 1:48am UTC
It's not std::string::substring() that's stopping at the space.
It's the use of the extraction operator >> with cin.
Try using std::string::getline instead.