如何使用逗号解析输入中的整数

how to parse integers from input with commas

本文关键字:输入 整数 何使用      更新时间:2023-10-16

我正在尝试弄清楚如何将整数提取到 int 向量中,以便我可以计算它们:

输入 = 40,50,29,50

*取出分隔符并将数字分成一个数组

arr[ ] = {40 50 29 50}

arr[0]+arr[1] = 90

我会喜欢没有 std::(又名使用命名空间 std;我更容易理解(

有人在这里举了一个例子,但我不知道它是否是同一件事或如何真正理解它。还有一个使用令牌的建议,但我也不确定如何做到这一点。任何事情都有助于谢谢!

您可以将整个输入存储为string,然后遍历它并将逗号之间的子字符串转换为整数:

#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
vector <int> nums;
string str;
cin >> str;
int lastcomma = -1;
while(str.find(',', lastcomma+1) != string::npos){ // find the next comma
int curr = str.find(',', lastcomma+1);
// stoi converts a string to an integer; just what you need
nums.push_back(stoi(str.substr(lastcomma+1, curr - (lastcomma+1))));
lastcomma = curr;
}

// get the last number
nums.push_back(stoi(str.substr(lastcomma+1, str.size()-(lastcomma+1))));

return 0;
}