gpt4 book ai didi

c++ - 在c++中搜索特定行后,如何在文件末尾附加文本?

转载 作者:行者123 更新时间:2023-12-02 10:09:18 25 4
gpt4 key购买 nike

我有一个文件,必须逐行搜索,然后从找到的行中找到第一个单词和第二个单词,然后在找到的行的末尾附加一个text(变量list_of_names)。我有以下代码,但是将文本附加到文件末尾,而不是在特定行上

    string line;
string courseid, course_section;
cout<<"What is a courseID: ";
cin>>courseid;
cout<<"What is the course section: ";
cin>>course_section;

string first;
ofstream outfile;
outfile.open("course_students.csv", ios_base::app);
ifstream file;
file.open("course_students.csv");

if(outfile.is_open()){
while(getline(file, line)) {
stringstream sst(line);
string section;

getline(getline (sst,first,','),section, ',');
//cout<<first<<endl;
if (courseid==first && course_section==section) {
//outfile<<save1;
outfile<<list_of_names;
}
}
}

outfile.close();
}
我的csv如下:
CSCI-UA.0465,1,
CSCI-UA.0473,1,
CSCI-UA.0470,1,
CSCI-UA.0453,1,
CSCI-UA.0421,1,
CSCI-UA.0310,1,
CSCI-UA.0201,1,
CSCI-UA.0102,5,
CSCI-UA.0101,2,
CSCI-UA.0101,1,
CSCI-UA.0061,1,
CSCI-UA.0060,1,
CSCI-UA.0004,4,
CSCI-UA.0004,1,
CSCI-UA.0002,3,
CSCI-UA.0002,2,
CSCI-GA.3033,13,
CSCI-GA.3033,10,
CSCI-GA.3033,2,
CSCI-GA.3033,1,
任何帮助将不胜感激!

最佳答案

下面这将在输出上创建一个新文件(course_students_output.csv),您可以随后对其进行重命名。

    string line;
string courseid, course_section;
cout<<"What is a courseID: ";
cin>>courseid;
cout<<"What is the course section: ";
cin>>course_section;

//string first;
ifstream file("course_students.csv");
ofstream outfile("course_students_output.csv");

if ( file.is_open() ) {
while ( getline(file, line) ) {
stringstream sst(line, ios_base::in | ios_base::app | ios_base::out);
outfile << sst.str();

string first, section;
getline(getline(sst,first,','), section, ',');
if (courseid==first && course_section==section) {
outfile << " " << list_of_names;
}
outfile << '\n';
}
}

file.close();
outfile.close();
}
如果还希望在文件末尾重复添加了 list_of_names的行,请通过以下方式在条件主体内添加一个新的 stringstream对象:
    // ... previous code from above
if ( file.is_open() ) {
stringstream end_sst(ios_base::in | ios_base::app | ios_base::out);
while ( getline(file, line) ) {
stringstream sst(line, ios_base::in | ios_base::app | ios_base::out);
outfile << sst.str();

string first, section;
getline(getline(sst,first,','), section, ',');
if (courseid==first && course_section==section) {
end_sst << line << " " << list_of_names << '\n';
outfile << " " << list_of_names;
}
outfile << '\n';
}
outfile << end_sst.str();
}
// add end lines from above...

关于c++ - 在c++中搜索特定行后,如何在文件末尾附加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64280354/

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