简体   繁体   English

我想接受用户输入并将其放入字符串数组c ++

[英]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. b未初始化,因此在首次用作索引时将具有随机值。 Initialise b and ensure array indexes do not go beyond the bounds of the array. 初始化b并确保数组索引不超出数组的范围。

Alternatively, use a std::vector<std::string> and operator>>() and forget about array indexes: 或者,使用std::vector<std::string>operator>>()并忽略数组索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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