复制字符串直到'。'以及当我知道结构时如何只复制数字

时间:2014-09-30 19:29:38

标签: c++ string

我有一个代码,我希望它从命令行获取输入文件,并在最后用XXX创建输出文件 - 如果intput =“blabla.txt”或“/johny/first/blabla.txt”我直到得到“blablaXXX.txt”或“/johny/first/blablaXXX.txt”

第二个问题是,当我找到一条我正在寻找的线路时,我只想复制数字(保持日期模式)和len

行将是“它在这里时间12:04:56.186,len 000120”

我想进入新的文件行:12:04:56.186 120

#include <iostream>
#include <fstream>

using namespace std;

int main( int argc, char* args[] )
{
    string inputName=args[1];

    ifstream  inputName(inputFileName);

    ////// here i will need to get the output string name some thing like
    // string outputFileName=EDITED_INPUT_NAME+"XXX"+".txt";

    ofstream outpuName(outputFileName);

        while( std::getline( inputName, line ) )
        {
                if(line.find("IT IS HERE") != string::npos)
                    // how to make it take only the parts i need??????
                    outpuName << line << endl;
                cout << line << endl;
        }


    inputName.close();
    outpuName.close();  
    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是否解决了您的问题:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main(int argc, char* args[]) {
    ifstream inputFile(args[1]);
    // Your first problem
    string outputFileName(args[1]);
    outputFileName.insert(outputFileName.find("."), "XXX");
    cout << "Writing to " << outputFileName << endl;
    // End of first problem

    ofstream outputFile(outputFileName.c_str());
    string line;

    while (getline(inputFile, line)) {
        if (line.find("IT IS HERE") != string::npos) {
            // Your second problem
            string::size_type time_start = line.find("time ") + 5;
            string::size_type time_end = line.find(",", time_start);
            cout << time_start << " " << time_end << endl;
            string time = line.substr(time_start, time_end - time_start);

            string::size_type len_start = line.find("len ") + 4;
            string::size_type len_end = line.find(" ", len_start);
            if (len_end != string::npos)
                len_end += 4;
            int len = atoi(line.substr(len_start, len_end - len_start).c_str());
            // End of second problem

            outputFile << time << " " << len << endl;
            cout << time << " " << len << endl;
        }
    }
    inputFile.close();
    outputFile.close();
    return 0;
}

示例输入:

sdfghjk sdfghjk fghjkl
IT IS HERE time 12:04:56.186, len 000120
usjvowv weovnwoivjw wvijwvjwv
IT IS HERE time 12:05:42.937, len 000140

示例输出:

12:04:56.186 120
12:05:42.937 140

使用std::regexauto代码可能看起来更好,但由于没有用C++11标记,我拒绝了。