简体   繁体   中英

I want to take user input and put it into an array of strings c++

I want to take in user input and put what they type into an array of strings. I want it to read each character and separate each word by white space. I am sure this is coded badly, although I did try to do it decent. I am getting a segmentation fault error and was wondering how I could go about doing this without getting the error. Here is the code I have.

#include <iostream>

using namespace std;

void stuff(char command[][5])
{ 
    int b, i = 0;
    char ch;
    cin.get(ch);

    while (ch != '\n')
    {
        command[i][b] = ch;
        i++;
        cin.get(ch);
        if(isspace(ch))
        {
            cin.get(ch);
            b++;

        }

    }
    for(int n = 0; n<i; n++)
    {
        for(int m = 0; m<b; m++)
            {
            cout << command[n][m];
            }
    }

}

int main()
{
    char cha[25][5];
    char ch;
    cin.get(ch);
    while (ch != 'q')
    {
        stuff(cha);
    }

    return 0;
}

b is not initialised so will have a random value when first used as the index. Initialise b and ensure array indexes do not go beyond the bounds of the array.

Alternatively, use a std::vector<std::string> and operator>>() and forget about array indexes:

std::string word;
std::vector<std::string> words;
while (cin >> word && word != "q") words.push_back(word);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM