读取字符串中的数字

原文链接:https://blog.csdn.net/qq_35976351/article/details/84799484

#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;

int main()
{
    string str("55.5818061829 119.6388702393 22.33");
    double t;
    istringstream iss;
    iss.str(str);
    while(iss>>t) {
        cout<<t<<endl;
    }
    return 0;
}

文件也能像“流”一样操作

#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;

int main()
{
    string str("55.5818061829 119.6388702393 22.33");
    double t;
    istringstream iss;
    iss.str(str);
    while(iss>>t) {
        cout<<t<<endl;
    }
    return 0;
}
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;

int main() {
    ifstream fin;
    istringstream iss;
    string s;
    double t;
    // 按行读取,每行的结束是回车区分
    fin.open("transform.txt");
    while(getline(fin, s)) {
        iss.clear();
        iss.str(s);
        while(iss>>t) {
            cout<<t<<" ";
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/friedCoder/p/12363646.html