gpt4 book ai didi

c++ - 制作空白输出文件的程序

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

所以我一直在研究类似 grep 的程序。这将搜索给定的文件,然后返回包含您想要的单词实例的所有行以及它出现的行号。我想出了这个:

#include <iostream>
#include <regex>
#include <string>
#include <fstream>
#include <vector>
#include <regex>
#include <iomanip>

using namespace std;

int main (int argc, char* argv[]){

// validate the command line info
if( argc < 2 ) {
cout << "Error: Incorrect number of command line arguments\n"
"Usage: grep\n";
return EXIT_FAILURE;
}

//Declare the arguments of the array
string query = argv[1];
string inputFileName = argv[2];
string outFileName = argv [3];
regex reg(query);

// Validate that the file is there and open it
ifstream infile( inputFileName );
if( !infile ) {
cout << "Error: failed to open <" << inputFileName << ">\n"
"Check filename, path, or it doesn't exist.\n";
return EXIT_FAILURE;
}



ofstream outFile (outFileName);
outFile.open( outFileName + ".txt" );
// if( !outFile ){
// cout << "Error: failed to create output file at " << outFileName << ".txt\n";
// return EXIT_FAILURE;
// }


//Create a vector of string to hold each line
vector<string> lines;

//Create a while loop that puts each line into the vector lines
string currentLine = "";
int currentLineNum = 0;

while(getline(infile,currentLine))
{
lines.push_back( currentLine );
currentLineNum++;
if( regex_match( query, reg ) )
outFile << "Line " << currentLineNum << ": " << currentLine;



}
outFile.close();
infile.close();
}

当我运行它时,它生成了文件,但文件最终是空白的,我确定我要搜索的内容在文件中,所以我想我在这里某处犯了逻辑错误。我没有制作输出文件的经验,但我写的似乎与我读过的语法相符。你们能提供的任何建议都将不胜感激。

最佳答案

看下面两行,为什么先调用constructor再调用open?

ofstream outFile (outFileName); // This does same thing as member function open
outFile.open( outFileName + ".txt" ); // <-- remove this line unnecessary

第二行将失败并设置 failbit,因此流处于错误状态(另外,您有 out.txt.txt)。

关于c++ - 制作空白输出文件的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9695262/

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