如何使用逗号解析输入中的整数
how to parse integers from input with commas
我正在尝试弄清楚如何将整数提取到 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;
}
相关文章:
- 如何打印不带空格的输入整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 如何在输入整数时中断 for 循环
- C++ 在 CIN 双精度时挂起,但如果输入整数,则继续
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何输入整数并将其从最高到最低排序
- 如何创建一个程序,用户输入整数并输出90度数字金字塔
- 使用对输入整数的文件输入
- 使用户输入整数字符串,然后输出不同的字符串
- 从 fstream 到 2d 矢量的输入整数<矢量<int>> C++
- 用户输入整数后跟垃圾
- 输入整数直到 C/C++ 中的换行符
- 输入整数的最快方法
- C++循环 - 输入整数,直到用户退出
- 尝试输入整数行并在以矢量作为存储的函数的插入排序类型中排序
- 如何使C++程序在用户输入整数时抛出错误,而需要字符串
- 当要求输入整数并使用isdigit检查时,将char转换为int
- 如何通过指针输入整数数组并打印出数组和数组的大小(C++)
- 如果打印后输入整数,则C++分段故障,但其他情况下可以