【发布时间】:2025-12-31 04:10:06
【问题描述】:
我正在将文件中的数据读取到名为data 的字符串向量中。对于这个数据向量,我通过名为output_string 的主函数推回一个新字符串。 Output_string 只是通过命令行传入的参数的组合。完成所有操作后,我写回我的文件(使用新字符串更新文件)。但是,当我这样做时,第一个命令行参数之后的所有内容,只要再次遇到data.push_back(output_string);,它就会跳过一个向量位置。
例如文件内容
bob
jack
snack
读入向量后,
数据向量内容
bob
jack
snack
添加新字符串后,新字符串“john”数据向量内容变为
bob
jack
snack
john
但是如果我再次运行程序并使用命令行再次添加一些东西,它会跳过一个向量位置
bob
jack
snack
john
peter
它对我在第一个之后添加的所有内容执行此操作。为什么要这样做?
int main (int argc, char *argv[]){
if (argc > 6){
cout<<"[Error] too many inputs provided" << endl;
return 0;
}
commandProcess(argc,argv);
outputstringformat();
//*********
if (cominput.rem_contpos == -1){
readData(); //reads data from a file into vector data
int outlen = output_string.length();
if (outlen > 0){
data.push_back(output_string); //pushing what i had in argv to vector
}
cout<<"----------data vector------------"<<endl;
for (int i = 0; i < data.size();i++){
cout<<"data: " << data[i] << endl;
}
ofstream outfile("contactlist.dat");
number_of_contacts = data.size();
if(outfile.is_open()){
for (int i =0; i < number_of_contacts; i++){
outfile << data[i] << endl; //copying evertthing back to file, including the new argument passed to data
}
outfile.close();
}
}
return 0;
}
编辑: 这也是我处理参数的方式,我将它们组合成一个字符串。我有一个暗示这可能是问题,但仍然没有看到它......:|
void outputstringformat(){
if (cominput.name1.length() != 0 ){
output_string = cominput.name1;
}
if (cominput.name2.length() != 0 ){
output_string = output_string + " " + cominput.name2;
}
if (cominput.name3.length() != 0 ){
output_string = output_string + " " + cominput.name3;
}
if (cominput.email.length() != 0 ){
output_string = output_string + " " + cominput.email;
}
if (cominput.phone.length() != 0 ){
output_string = output_string + " " + cominput.phone;
}
}
用 reaData 更新
void readData(){
ifstream myfile("contactlist.dat");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
data.push_back(line);
}
myfile.close();
}
}
【问题讨论】: