tags:

views:

254

answers:

2

Noob to C++.

I'm trying to get user input (Last Name, First Name Middle Name), change part of it (Middle Name to Middle Initial) and then rearrange it (First Middle Initial Last).

Where am I messing up in my code?

--Thanks for ANY help you can offer!

...

#include <iostream>
using std::cout;
using std::cin;

#include <string>
using std::string;

int main()
{

  string myString, last, first, middle;

  cout << "Enter your name: Last, First Middle";

  cin >> last >> first >> middle;

  char comma, space1, space2;

  comma = myString.find_first_of(',');
  space1 = myString.find_first_of(' ');
  space2 = myString.find_last_of(' ');

  last = myString.substr (0, comma); // user input last name
  first = myString.substr (space1+1, -1); // user input first name
  middle = myString.substr (space2+1, -1); // user input middle name

  middle.insert (0, space2+1); // inserts middle initial in front of middle name
  middle.erase (1, -1); // deletes full middle name, leaving only middle initial

  myString = first + ' ' + middle + ' ' + last; //  

  return 0;
}
+12  A: 

shouldn't this line :

cin >> last >> first >> middle;

be

cin >> myString;

?

Because after that you search for the comma and spaces in myString but this string contains nothing.

p4bl0
That won't work, because it will stop reading the line at the first space.
Johannes Schaub - litb
How'd this get so many upvotes... it won't work unless they enter their names without spaces...
DeusAduro
@DeusAduro i didn't understand that either, That's why i upvoted litb's comment and anwser. JW should accept litb's answer so it goes up in the page and get highlighted.
p4bl0
+12  A: 

Well you search for things in myString but never set it to anything (it's an empty string).

You should read one whole line into myString.

std::getline(std::cin, myString);

Then you can look out for the , and spaces etc. The second problem is that you should use size_t as the type of comma, space1 and space2. These keep the positions of the spaces and commas in the string: If the comma or space isn't found in input, then the find functions return string::npos, which is the highest value in a size_t. But this would overflow a char. For reliably assigning the position, you should thus change the type of these three variables to size_t.

Then instead of using -1 to say that you want to extract a substring until end just omit it: It has a default argument for that parameter which specifies string::npos. If you really want to pass it, maybe because it improves readability for you, use string::npos instead: It has the right type (size_t), and won't need a conversion of int (with value -1) to it.

Johannes Schaub - litb