c++ 一次性读入一行数字 并转换成int数组

c++ 一次性读入一行数字 并转换成int数组,第1张

#include 
#include 
#include 
#include 
using namespace std;


void Stringsplit(string str,const char split,vector<string>& rst)
{
    istringstream iss(str);    // 输入流
    string token;        // 接收缓冲区
    while (getline(iss, token, split)) // 以split为分隔符
    {
        rst.push_back(token);
    }
}

int main() {

    string mystr;
    getline(cin, mystr, '\n');//一次读取一行
    cout << "getline:" << endl;
    cout << mystr << endl;

    vector<string> strList;
    Stringsplit(mystr, ' ', strList);  // 以空格为分割 将子串存放到strList中
    int res[strList.size()]; //结果数组 将分割后的strList转化为int 并保存到此数组中
    for (int i = 0; i < strList.size(); ++i) {
        res[i]=atoi(strList.at(i).c_str());//将string转为int
    }
    cout << "res:" << endl;
    for (auto out:res) {
        cout<<out<<" ";
    }
    cout << endl;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/579049.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-11
下一篇 2022-04-11

发表评论

登录后才能评论

评论列表(0条)

保存