C++ 将包含数字的字符串解析为整数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17724925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:23:34  来源:igfitidea点击:

Parse string containing numbers into integer array

c++arraysstringparsing

提问by djadmin

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

字符串作为由数字组成的输入给出,我想在 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;
}

Output(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 ?

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

UPDATE:

更新:

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

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

回答by Sebastian Mach

The end of file condition is notset upon a succesfulparse, you have to check the state of the stream after parsing.

解析成功后不会设置文件结束条件,您必须在解析后检查流的状态。

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

第二个76基本上只是纯粹的机会。不成功的解析会保持目标操作数不变,并且因为您没有 initialize n,它可以是任何东西。

A quickfix:

快速修复:

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

A cleaner fix:

更清洁的修复:

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

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

要存储这些整数,规范的方法是在std::vector元素数量未知时使用。一个示例用法:

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

回答by Thacious

Another means of dealing with a character separated integers list using a vector, which is even perhaps a little more simplistic is more like this:

使用向量处理字符分隔的整数列表的另一种方法,甚至可能更简单一点,更像是这样:

string str = "50,2,25,38,9,16";
vector<int> ints;
stringstream ss(str);
int n;
char ch;

while(ss >> n) {
    if(ss >> ch)
        ints.push_back(n);
    else
        ints.push_back(n);
}

that way you can move past any character separations (if they exist) first and then default back to grabbing the integers and adding them to the list if they don't (AKA the end of the list)

这样你就可以先移过任何字符分隔(如果它们存在),然后默认返回获取整数并将它们添加到列表中(如果它们不存在)(也就是列表的末尾)

回答by Duc Nguyen

i don't know if you find the answer for your updated question or not. if you don't you can easily do it by the code

我不知道您是否找到了更新问题的答案。如果不这样做,您可以通过代码轻松完成

for (string::iterator it = num.begin(); it != num.end(); ++it) {
    if (*it == ',') {
        *it = ' ';
    }
    else continue;
}

this code removes all your colons and replaces them by space. then you can do just normally

此代码删除所有冒号并用空格替换它们。那么你就可以正常进行