There are a few blatant errors in your code:
- You need to always check your input after trying to read! You do that using the
while
-loop but you also need to verify that you actually successfully read the string first. - It seems you are mixing the what the input operator for
std::string
andstd::getline()
are doing: the input operator reads the first word after skipping leading spaces whilestd::getline()
read, well, a line (whether the line terminator can be specified as third argument). - When reading fixed sized array you always need to make sure you do not read more than fits into this array! You may have heart about hackers exploiting software by using buffer overruns: assuming you'd actually indeed read a line first followed by splitting it into words you'd have created one of those exploitable programs! If you don't want to check before each word if there is enough space in the array, you'd use, e.g., a
std::vector<std::string>
(doing so also has a problem with hackers, namely that it opens up the program for a Denial of Service attack but although this is still a problem it is a somewhat lesser problem).
There are also a few smaller issues with your program, too:
- If you are only reading from a string stream, you should use
std::istringstream
as there is no need to also set up the writing part of thestd::stringstream
. - The programs asks for "first name, middle name, and last name". I would read that specification to use, e.g., "John, F., Kennedy" but it seems you'd expect "John F. Kennedy". One reason I would expect that commas are to be used is that I don't have a middle name, i.e., I would enter "Dietmar, , Kühl".