Hey guys so I have an assignment for class where I have to split a string and manipulate it. However, when I try to split the string and assign it to an array only the first element comes and the other two don't. Please help.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string str;
    cout<<"Enter a first name, middle initial, last name: ";
    cin>> str;
    string word;
    string array[3];
    stringstream stream(str);
    int counter = 0;
    while( getline(stream, word, ' ') )
    {
        cout<<word;
       array[counter] = word;

       counter++;
    }
    cout<<"The "<<array[0].length()<<" characters of the first name are: "<<array[0]<<endl;
    cout<<"The "<<array[2].length()<<" characters of the last name are: "<<array[2]<<endl;
    string newstring = array[2]+", "+array[0]+" "+array[1];
    cout<<"In the phone book, the name would be: "<<newstring<<endl;
    cout<<"The length of the name is: "<<newstring.length()<<endl;
    cout<<"The comma is at position: "<<newstring.find(",")<<endl;
    array[0].swap(array[2]);
    cout<<"After the swap, the last name is "<<array[2]<<" and the first name is "<<array[0];

    system("pause");
    return 0;

}
有帮助吗?

解决方案

There are a few blatant errors in your code:

  1. 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.
  2. It seems you are mixing the what the input operator for std::string and std::getline() are doing: the input operator reads the first word after skipping leading spaces while std::getline() read, well, a line (whether the line terminator can be specified as third argument).
  3. 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:

  1. 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 the std::stringstream.
  2. 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".
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top