【问题标题】:sstream class to read integers from character array [closed]sstream 类从字符数组中读取整数
【发布时间】:2020-04-09 12:57:45
【问题描述】:

我还没有看到使用 stringstream 从字符数组中读取整数列表的任何适当应用。

元素应作为空格分隔的字符串/(字符数组)输入一行,并使用 sstream 类执行必要的转换。

这应该在不使用向量或任何其他附加 STL 容器(仅 std::string 和 char 数组)的情况下完成,结果整数数组的长度应存储在变量中。

执行此类操作的最有效方法是什么?

【问题讨论】:

  • 实际上有数百个使用stringstream 从字符串中读取整数的示例。或者您想实现自己的stringstream
  • 您能否提供一个工作示例,说明用户提供的字符串被读取并通过 stringstream 转换为整数数组?

标签: c++ arrays string iostream stringstream


【解决方案1】:

假设我明白你的意思,那么

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

int main() {
    std::string apples;
    std::getline( std::cin, apples );

    std::istringstream iss( apples );

    std::vector<int> vec;
    int val;

    while ( iss >> val ) {
        vec.push_back( val );
    }

    for ( int i : vec ) {
        std::cout << i << ',';
    }
}

【讨论】:

  • 不使用向量,将输入存储到整数数组(指针)中。
  • 从现有的vector 转换为数组很简单。
【解决方案2】:

这更符合我的意思。

int* theheap = new int[10];
std::string num;
int val = 0;
int size = 0;
std::cout << "Enter the elements of heap" << std::endl;
std::getline( std::cin, num );
std::istringstream iss(num);    
while ( iss >> val ) {
   if (val != ' '){
      theheap[size] = val;
      ++size;
   }
}

【讨论】:

  • 您不必与' ' 进行比较,事实上,这会使其忽略数字32。因为iss &gt;&gt; val 已经读取整数,并跳过空格。
猜你喜欢
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
相关资源
最近更新 更多