Simple C++ Substring Issue

The program does not properly find the substrings of each section of the name "John Fitzgerald Kennedy", and cannot output each name on a separate line. The program outputs a out of range exception and does not even show the second name, only the first. How would I ouput each name on each separate line?

#include <iostream>
#include <string>

using namespace std;

int main()
{

string fullName="",
        firstName="",
        middleName="",
        lastName="";

cout<<"Enter your full name: ";
cin>>fullName;

firstName=fullName.substr(0,4);
middleName=fullName.substr(4,14);
lastName=fullName.substr(14,19);

cout<<firstName<<endl;
cout<<middleName<<endl;
cout<<lastName;

cin.get();
cin.get();

return 0;
}

Answers


cin>>fullName;

stops reading the standard input when it encounters the first space. What you need is a command like

getline(cin, fullName);

to read the entire line along with the spaces and then chunk them to get different parts of the name.


One more thing to note is that:

firstName=fullName.substr(0,4);
middleName=fullName.substr(4,14);
lastName=fullName.substr(14,19);

The second parameter in substr is the length of the substring, NOT the end index of the substring, if you do not mean that your first name is 4 characters long, middle name is 14 characters long, etc, you probably need to update them to the following:

firstName=fullName.substr(0,4);
middleName=fullName.substr(4,10);
lastName=fullName.substr(14,5);

Need Your Help

I m stuck with jquery load with asp.net

jquery asp.net html

I m stuck with jquery load. this is my code .

SQL query doesn't finish

sql performance

I run script, that select from table:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.