gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:40:06 25 4
gpt4 key购买 nike

我有一个代码,我希望它从命令行获取输入文件并在末尾创建带有 XXX 的输出文件 - 这意味着如果 intput= "blabla.txt"或 "/johny/first/blabla.txt"我直到获取“blablaXXX.txt”或“/johny/first/blablaXXX.txt”

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

行将是“IT IS HERE time 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;
}

最佳答案

这是否解决了您的问题:

#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 标记,我忍住了。

关于c++ - 复制字符串直到 '.' 以及当我知道结构时如何只复制数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26128597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com