函数功能:
输入数组格式12,12,1,4,-1
输出vector数组vec={12,12,1,4,-1}
#include <iostream> #include <string> #include <vector> using namespace std; int strNum(string str) { //字符串转数字,包括负数判断 int num = 0; int flag = 1; for(int i = 0; i < str.size(); i++) { if(str[i] == '-') flag *= -1; else { num = num * 10 + (str[i] - '0'); } } return num * flag; } int main() { string str; cin >> str; //输入字符串 vector<int> vec; string num_str; for(int i = 0; i < str.length(); i++) { if(str[i] != ',') { num_str += str[i]; } else { vec.push_back(strNum(num_str)); num_str = ""; } } vec.push_back(strNum(num_str));//输入的数组保存在vec中 //显示输入的数组 for(int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } cout << endl; return 0; }
结果显示