我正在将文件中的数据读入到名为data
的字符串向量中。对于这个数据向量,我通过称为output_string
的主要push_back一个新字符串。 Output_string只是通过命令行传入的参数的组合。完成所有我写回我的文件后(使用新字符串更新文件)。但是,当我这样做时,第一个命令行参数后面的所有内容,只要遇到data.push_back(output_string);
,就会跳过一个向量位置。添加新的字符串当push_back跳过向量位置
例如文件内容
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();
}
}
非常感谢你! – silent 2010-08-22 23:18:32