【问题标题】:I want to take user input and put it into an array of strings c++我想接受用户输入并将其放入字符串数组 c++
【发布时间】:2012-12-09 09:11:06
【问题描述】:

我想接受用户输入并将他们输入的内容放入字符串数组中。我希望它读取每个字符并用空格分隔每个单词。我敢肯定这是编码错误,尽管我确实尝试过做得很好。我收到分段错误错误,想知道如何在不出现错误的情况下执行此操作。这是我的代码。

#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;
}

【问题讨论】:

  • 为什么不使用std::vector&lt;std::string&gt; &gt; 并将cin 应用于字符串?

标签: c++


【解决方案1】:

b 未初始化,因此在首次用作索引时将具有随机值。初始化 b 并确保数组索引不会超出数组的边界。

或者,使用 std::vector&lt;std::string&gt;operator&gt;&gt;() 并忘记数组索引:

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

【讨论】:

  • 谢谢!每当我使用空格时,我都会在数组中得到奇怪的字符。你知道什么可以解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2021-07-19
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多