【问题标题】:read string into array将字符串读入数组
【发布时间】:2015-09-30 02:52:38
【问题描述】:

我想将带有整数和空格的字符串读入数组。例如,我有一个看起来像 1 2 3 4 5 的字符串,我想将其转换为整数数组 arr[5]={1, 2, 3, 4, 5}。我该怎么做?

我试图删除空格,但这只是将整个 12345 分配给每个数组元素。如果我不把所有元素都赋值为 1。

for (int i = 0; i < str.length(); i++){
            if (str[i] == ' ')
                str.erase(i, 1);
        }

for (int j = 0; j < size; j++){   // size is given

            arr[j] = atoi(str.c_str());

        }

【问题讨论】:

  • 为什么不使用vector
  • @user657267 是的,但有点倾斜。王牌,stringstream input("1 2 3 4 5"); 然后while (input &gt;&gt; arr[i] &amp;&amp; i &lt; MAX_I);更好,while(input &gt;&gt; temp) vec.push_back(temp);

标签: c++ arrays string


【解决方案1】:

几点说明:

  • 使用std::vector。您很可能在编译时永远不会知道输入的大小。如果您这样做,请使用std::array
  • 如果您有可用的 C++11,不妨考虑 stoistol,因为它们会在转换失败时抛出
  • 您可以使用std::stringstream 完成您的任务,这将允许您将std::string 视为std::istream,就像std::cin。我推荐这种方式
  • 或者,您可以采取艰难的方式并尝试基于 ' ' 作为分隔符来标记您的 std::string,这似乎是您正在尝试做的事情。
  • 最后,如果你走标记化路线,为什么要重新发明轮子?使用 Boost 的 split 函数。

字符串流方法

std::vector<int> ReadInputFromStream(const std::string& _input, int _num_vals)
{
    std::vector<int> toReturn;
    toReturn.reserve(_num_vals);
    std::istringstream fin(_input);
    for(int i=0, nextInt=0; i < _num_vals && fin >> nextInt; ++i)
    {
        toReturn.emplace_back(nextInt);
    }

    // assert (toReturn.size() == _num_vals, "Error, stream did not contain enough input")
    return toReturn;
}

标记化方法

std::vector<int> ReadInputFromTokenizedString(const std::string& _input, int _num_vals)
{
    std::vector<int> toReturn;
    toReturn.reserve(_num_vals);
    char tok = ' '; // whitespace delimiter
    size_t beg = 0;
    size_t end = 0;
    for(beg = _input.find_first_not_of(tok, end); toReturn.size() < static_cast<size_t>(_num_vals) &&
    beg != std::string::npos; beg = _input.find_first_not_of(tok, end))
    {
        end = beg+1;
        while(_input[end] == tok && end < _input.size())
            ++end;
        toReturn.push_back(std::stoi(_input.substr(beg, end-beg)));
    }
    // assert (toReturn.size() == _num_vals, "Error, string did not contain enough input")
    return toReturn;
}

Live Demo

【讨论】:

  • 如果在编译时知道大小,有没有办法使用数组?
  • @Ace_J,绝对。假设toReturn 在我上面的例子中是std::array。您将改为执行分配而不是 push_back。即toReturn[index] = stoi(...)
【解决方案2】:

您的代码arr[j] = atoi(str.c_str()); 有问题。 strstring,而不是 char。当你使用atoi(const char *) 时,你应该给出&amp;char 参数。所以正确的代码是arr[j] = atoi(&amp;str[j])。顺便说一句,如果要将string 更改为int,可以使用函数arr[j] = std::stoul(str)。我希望这可以帮助你。

【讨论】:

    【解决方案3】:

    您已在一个循环中修改/解析字符串,但在另一个循环中复制到整数数组。不设置任何标记,字符串中的所有嵌入整数开始/结束。所以我们必须在一个循环中完成这两个动作。 这段代码并不完美,但能给你一些想法;遵循与您相同的过程,但使用了向量。

    string str = "12 13 14";
    vector<int> integers;
    int start=0,i = 0;
    for (; i < str.length(); i++){
            if (str[i] == ' ')
            {
                integers.push_back(atoi(str.substr(start,i).c_str()));
                start = i;
            }
        }
    integers.push_back(atoi(str.substr(start,i).c_str()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多