将包含数字的字符串解析为整数数组 [英] Parse string containing numbers into integer array

查看:24
本文介绍了将包含数字的字符串解析为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个字符串作为由数字组成的输入给出,我想在 C++ 中将其转换为整数数组.

A String is given as an input which consists of numbers and I want to convert it into integer arrays in C++.

#include <string>
#include <iostream>
#include <sstream>

using std::string;
using std::stringstream;
using std::cout;
using std::endl;

int main(int argc,char** argv) {

    string num="-24 2 90 24 50 76";

    stringstream stream(num);

    while(stream){
        int n;
        stream>>n;
        cout<<n<<endl;
    }

    return 0;
}

输出(GCC):

-24 2 90 24 50 76 76

-24 2 90 24 50 76 76

为什么我会获得额外的价值,将它们转换为整数数组的效率是多少?

Why am i getting extra value and what is the efficient to convert them into integer array ?

更新:

如果字符串流包含除空格以外的分隔符怎么办,如何解析?例如:string num="-24,2,90,24,50,76";

What if the string stream contains delimiter other than space, How to parse this? For eg: string num="-24,2,90,24,50,76";

推荐答案

文件结束条件 not 设置在 succesful 解析,你必须检查状态解析后的流.

The end of file condition is not set upon a succesful parse, you have to check the state of the stream after parsing.

第二个 76 基本上只是偶然.不成功的解析会保持目标操作数不变,因为您没有初始化 n,它可以是任何东西.

The second 76 is basically just pure chance. An unsuccesful parse leaves the target operand untouched, and because you did not initialize n, it can be anything.

快速修复:

stream>>n;
if (stream)
    cout<<n<<endl;

更干净的修复:

int n;
while(stream >> n){
    cout<<n<<endl;
}

要存储这些整数,如果元素数量未知,规范的方法是使用 std::vector.示例用法:

To store those integers, the canonical way is to use std::vector if the number of elements is unknown. An example usage:

std::vector<int> values;
int n;
while(stream >> n){
    ...do something with n...
    values.push_back(n);
}

但是,您可以在流上使用迭代器并使用以下内容:

However, you can use iterators over streams and use the following:

// Use std::vector's range constructor
std::vector<int> values(
     (std::istream_iterator<int>(stream)), // begin
     (std::istream_iterator<int>()));      // end

这篇关于将包含数字的字符串解析为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆