从getline()读取逗号分隔的整数 [英] Read comma separated integers from getline()

查看:51
本文介绍了从getline()读取逗号分隔的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从下面的代码中读取单独的整数?

How can I read separate integers from the code below?

while (getline(cin, line)) {
    // for each integer in line do something.....
    // myVector.push_back(each integer)
}

输入是这样的: 1、2、3、5 (除最后一个整数外,用逗号分隔).

The input is like this: 1, 2, 3, 5 (separated by comma except the last integer).

样本输入(忽略行号部分):

Sample Input (ignore the line # part):

 line1: 1, 2, 3, 4, 5
 line2: 6, 7, 8, 9, 10
 line3: 3, 3, 3, 3, 3
 /// and so on...

我需要一个一个地读取整数,让我们说一下增量并打印它们.

I need to read the integers one by one, and let's say increment and print them.

推荐答案

默认情况下,'\ n' std :: getline()的分隔符.您可以指定','作为分隔符,例如:

By default, '\n' is the delimiter for std::getline(). You can specify ',' instead as the delimiter, eg:

string value;
while (getline(cin, value, ',')) {
    int num = stoi(value);
    ...
}

否则,您可以将 std :: getline()'\ n'用作分隔符,以读取整行,然后使用单独的std :: istringstream 从该行读取值,例如使用 std :: getline()','作为分隔符,例如:

Otherwise, you can use std::getline() with '\n' as the delimiter to read an entire line, and then use a separate std::istringstream to read values from that line, such as by using std::getline() with ',' as the delimiter, eg:

string line;
if (getline(cin, line)) {
    istringstream iss(line);
    string value;
    while (getline(iss, value, ',')) {
        int num = stoi(value);
        ...
    }
}

或者,您可以通过 operator>> 使用流提取,例如:

Alternatively, you can use streaming extraction via operator>>, eg:

string line;
if (getline(cin, line)) {
    istringstream iss(line);
    int num;
    while (iss >> num) {
        ...
        iss.ignore(); // skip terminating comma/whitespace
    }
}

这篇关于从getline()读取逗号分隔的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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