【发布时间】:2018-07-27 23:48:48
【问题描述】:
我有这样的文字
学生 = 321321
姓名 = 詹妮弗·劳伦斯
课程 = 公关
电话号码 = 790-3233
我只想将等号后的数据存储到student->id、student->name、student->course、student->phone_no中
Student *student[100];
string str, line;
char * temp;
ifstream inFile;
inFile.open(fileName);
if (!inFile.is_open())
return false;
else
{
for(int i=0; i<100;i++)
{
for (int j=0; getline(inFile, line) && j < 4; j++)
{
if (line.compare(0, 7, "Student") == 0)
{
size_t pos = line.find("=");
temp = line.substr(pos + 2);
strcpy(student[i]->id, temp);
}
else if (line.compare(0, 4, "Name") == 0)
{
size_t pos = line.find("=");
temp = line.substr(pos + 2);
strcpy(student[i]->name, temp);
}
else if (line.compare(0, 6, "course") == 0)
{
size_t pos = line.find("=");
temp = line.substr(pos + 2);
strncpy(student[i]->course, temp);
}
else if (line.compare(0, 5, "Phone") == 0)
{
size_t pos = line.find("=");
temp = line.substr(pos + 2);
strcpy(student[i]->phone_no, temp);
}
}
}
return true;
}
错误发生在temp = line.substr(pos + 2); 行
它说:
no suitable conversion function from "std::basic_string<char, std::char_traits<char>, std::allocator<char>>" to "char *" exists"
【问题讨论】:
-
将错误信息放在您的问题中,而不是在图片中。同时创建一个Minimal, Complete, and Verifiable example。
-
对不起,我已经编辑了,请检查一下
-
请添加
Student的定义。更好的是,把它变成minimal reproducible example。 -
只需使用
std::string。char*是一种 c-ism,你应该尽可能避免。 -
警告:
Student *student[100];是一个包含 100 个指向Student的指针的数组。您绝不会分配任何Students。考虑用Student student[100];或std::vector<Student> student;替换它,并使用push_back或emplace_back方法填充vector。