【问题标题】:Writing a vector to a output file c++将向量写入输出文件c ++
【发布时间】:2020-08-29 05:54:11
【问题描述】:

这里我有一个叫做contacts的结构

 typedef struct contacts 
    {
       string name;   //{jhonathan , anderson , felicia}
       string nickName; //{jhonny  , andy , felic}
       string phoneNumber; // {13453514 ,148039 , 328490}
       string carrier;  // {atandt , coolmobiles , atandt }
       string address; // {1bcd , gfhs ,jhtd }
    
    } contactDetails;
    
    vector <contactDetails> proContactFile;

我正在尝试将向量中的数据写入输出文件。为此,我编写了以下代码

ofstream output_file("temp.csv");
int selectContact;
cout << "Which Contact you want to delete ? Enter the relevent index " << endl;
cin >> selectContact;

if (selectContact > proContactFile.size()) {
    cout << "Invalid entry";
}
else {
    proContactFile.erase(proContactFile.begin() + (selectContact - 1));
    cout << "Delete successfully";
}
  
  ostream_iterator<contactDetails> output_iterator(output_file, "\n");
  copy(begin(proContactFile),end(proContactFile), output_iterator);  
}
output_file.close();
fin.close();
remove("Contact.csv");//Deletes contacts.csv file
rename("temp.csv" , "Contact.csv");

但是这段代码总是给我一个错误。另外我想用以下方式将数据写入文件。

Name,Nick name,Phone number,Carrier,Address

我的代码有什么问题?(基本上我在这里做的是让用户删除向量中的一个元素并将更新的向量写入输出文件)

这是我收到的错误:Error C2679 binary '&lt;&lt;': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)

【问题讨论】:

  • 这里的意思是你已经成功地将你的数据写入到你代码的另一部分的文件中。那么这段代码和好代码有什么区别,或者为什么这里不能用好代码代替上面的呢?
  • 不要让我们猜测,说出错误是什么。我有一个想法,但您最好确认一下。
  • 你遇到了什么错误?
  • ofstream output_file 已被声明了两次...这是错字吗?
  • @john 我真的很抱歉。我得到的错误是Error C2679 binary '&lt;&lt;': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)

标签: c++ vector file-io


【解决方案1】:

所以使用这种写向量的技术

ostream_iterator<contactDetails> output_iterator(output_file, "\n");
copy(begin(proContactFile),end(proContactFile), output_iterator); 

要求您为结构重载operator&lt;&lt;。即

ostream& operator<<(ostream& out, const contactDetails& details)
{
    // your output code here, e.g.
    out<< details.name << ',' << details.nickName << ','; //etc << ...
    return out;
}

但令人费解的问题仍然存在。上面的代码用于更新文件。这意味着您已经有一个文件。这意味着您已经在代码的其他位置成功地编写了该文件。你是怎么做到的?

无论您如何管理它,您都应该更新其他代码,以便它使用您要编写的operator&lt;&lt; 来修复此代码。这样,您的所有联系方式输出都会通过一个函数。

【讨论】:

  • 我试过这个东西,伙计。但它仍然说expected a ';'。但什么都没有
  • 它仍然写着expected a ';'pal
  • @SeektheFreak2 我无法诊断您的代码出了什么问题,除非我能看到它。
猜你喜欢
  • 2013-03-26
  • 2020-12-17
  • 1970-01-01
  • 2023-03-06
  • 2019-10-27
  • 2018-08-13
  • 1970-01-01
  • 2020-05-24
  • 1970-01-01
相关资源
最近更新 更多