C++常用代碼案例

目錄

1、讀取market.txt配置文件,取出其中逗號分割的字符串,並輸出到新的文件中。


1、讀取market.txt配置文件,取出其中逗號分割的字符串,並輸出到新的文件中。

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <vector>

using namespace std;

//分割字符串, s爲原始字符串,v爲分割後的字符串,c爲分隔符
void splitString(string& s, std::vector<std::string>&v, const string& c);

int main()
{
//    ifstream ifs;
//    ifs.open("market.txt");
    ifstream ifs("market.txt");
    if(!ifs.is_open())
    {
        cerr << "open file failed" << endl;
        exit(-1);
    }

    ofstream ofs("out.txt");
    if(!ofs.is_open())
    {
        cerr << "create file failed" << endl;
        exit(-1);
    }

    string str;
    string c = ",";
    
    while(getline(ifs, str))
    {
        vector<string> market_code;
        splitString(str, market_code, c);
        ofs << market_code[0] << " " << market_code[1] << endl;
        //cout << str << endl;
    }
    ifs.close();
    ofs.close();

return 0;
}

void splitString(string& s, std::vector<std::string>&v, const string& c)
{
        //處理每一行後面的“\r\n”
        size_t n = s.find_last_not_of("\r\n");
        if(n != string::npos)
        {
            s.erase(n+1, s.size() -n);
        }
        n = s.find_first_not_of("\r\n");
        if(n != string::npos)
        {
            s.erase(0, n);
        }

        string::size_type pos1, pos2;
        pos2 = s.find(c);
        pos1 = 0;
        while(string::npos != pos2)
        {
            v.push_back(s.substr(pos1, pos2-pos1));

            pos1 = pos2 + c.size();
            pos2 = s.find(c, pos1);
        }
        if(pos1 != s.length())
        {
            v.push_back(s.substr(pos1));
        }
}

//market.txt
2,000001
1,600519
2,000002

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章