将substr存储到另一个变量中以进行进一步分配

时间:2018-07-27 23:48:48

标签: c++ string stl

我有这样的文字

学生= 321321

名称= Jennifer Lawrence

课程= PR

电话号码= 790-3233

我只想将等号后的数据存储到student->idstudent->namestudent->coursestudent->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"

2 个答案:

答案 0 :(得分:1)

std::string::substr()返回std::string,而不是char*。您可以使用std::string::c_str()来获得const char*所需的strcpy,而不必担心温度:

strcpy(student[i]->id, line.substr(pos + 2).c_str());

但是,我看不到您为Student::id分配了存储空间,它是数组吗?即使分配了存储空间,也永远不会检查是否有足够的空间。我强烈建议不要将Student::id设为std::string,而不是那样做,这很容易:

student[i]->id = line.substr(pos + 2);

答案 1 :(得分:0)

您必须为学生[i]管理内存分配和免费。

1)使用nullptr初始化指针数组:

Student * student[100]{ nullptr };

2)在分配student[i] = new Student对象之前,先为其分配值。

3)并在退出前免费分配:

for (int i=0; i<100; i++) {
    If (student[i] != nullptr)
        delete student[i];
}

-

更好的做法是使用智能指针:

#include <array>
#include <memory>

// Declare student array:
std::array<std::unique_ptr<Student>, 100> student;

// Allocate a new Student object (since C++14):
student[i] = std::make_unique<Student>(); // Preferred, over C++11 method

// (Or instead,) allocate a new Student object (since C++11):
student[i].reset(new Student); // If no support for C++14

// Now, it's OK to assign to student[i]:
// strcpy(student[i]->id, temp);

// ** No need to free allocations. **

-

(除了@zdan给您写的内容。)