c++ - 文件保存错误 [错误] 无法传递非平凡可复制类型的对象 'std::string {aka class std::basic_string}' 通过 '...'
问题描述
我在编码世界中很新,所以我似乎无法理解这个错误。fprintf
我正在创建一个产品管理程序,您可以在其中输入产品详细信息并将该数据放在文件中,然后通过 cmd 从文件中查看它,但是每当我使用或时,此错误都会不断弹出fputs
。
我的代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
struct product{
string Id,Name,Brand;
int type, price, quan;
product *next;
};
int main(){
product *a,*b,*c,*d,*e,*f;
a = new product;
b = new product;
c = new product;
d = new product;
e = new product;
f = new product;
FILE *productRecord;
productRecord = fopen("Product Record","r");
int choice;
cout << "\nProduct Record\n1)Add Product\n2)Update Product Details\n3)Delete Product\n4)View Product By Brand or Type\n5)Exit\n\nEnter Choice: ";
cin >> choice;
if(choice == 1){
char tempId[11],tempName[60],tempBrand[60];
int temp_type, temp_price, temp_quan;
productRecord = fopen("Product Record","a");
cout << "Enter Product ID No.(Maximum of 10 Digits): ";
cin >> tempId;
a -> Id = tempId;
a -> next = b;
cout << "Enter Product Name(No Special Character): ";
cin >> tempName;
b -> Name = tempName;
b -> next = c;
cout << "Types:Canned(1),Frozen(2),Drinks(3),Produce(4),Meat/Seafood(5),Cleaning(6)\nEnter Product Type(1-6): ";
cin >> temp_type;
c -> type = temp_type;
c -> next = d;
cout << "Enter Product Brand(No spaces): ";
cin >> tempBrand;
d -> Brand = tempBrand;
d -> next = e;
cout << "Enter Product Price: ";
cin >> temp_price;
e -> price = temp_price;
e -> next = f;
cout << "Enter Product Quantity: ";
cin >> temp_quan;
f -> quan = temp_quan;
f -> next = NULL;
fprintf(productRecord, "%s", a -> Id); //this is the error
fclose(productRecord);
}
else if(choice == 2){
}
else if(choice == 3){
}
else if(choice == 4){
}
else if(choice == 5){
}
return 0;
}
解决方案
错误信息非常清楚。您不能使用string
with fprintf
。
fprintf(productRecord, "%s", a -> Id);
需要改为
fprintf(productRecord, "%s", a->Id.c_str());
或者,更好的是,不要混合使用 C 和 C++,而是使用ofstream
推荐阅读
- go - 从父包全局初始化内部包全局?
- c# - 如何在 C# 中处理此强制转换异常:system.windows.controls.CheckBox 中的 system.data.model?
- c# - Windows Service 内存使用量稳步增长
- flutter - 奖励用户完成任务
- java - 日志记录过于频繁会导致堆大小急剧增加吗?
- python - 如何在 json 中作为后端发布?
- matlab - 在matlab中以递归方式对决胜局进行排序
- jquery - jQuery:将元素包装在多个 div 中
- python - 为什么Django rest框架中的“HyperlinkedRelatedField”需要它的视图来返回“request”参数作为上下文?
- git - 如何告诉 git 忽略对已提交文件的更改?