I am beginner in C++, I am trying to put text into a vector from a textfile by using tokens with strtok_s.

I can get just one text pushed back and displayed in the vector and I sure that there are some problems in my coding.

Here are the codes :

    std::vector<char> myVector;
    ifstream myReadFile;
    myReadFile.open("E:/C++/Projects/Textfile project/Textfile project/class_data.txt", ios_base::in); 
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            myReadFile >> output;
        }

    }
    myReadFile.close();

    char* token = NULL;
    char* context = NULL;
    char delims[] = " ,\t\n";


    token = strtok_s(output, delims, &context);

    while (token != NULL)
    {
        if (token != NULL) 
        {
            myVector.push_back(token);
            token = strtok_s(NULL, delims, &context);

        }
    }

    for (int i = 0; i < myVector.size(); i++) {
        cout << myVector[i] << endl;
    }

I am trying to get the text out of the text file, separate it into individual parts and put them into a vector of chars.

Can anyone tell me what mistakes I have done ? And sorry for not professional coding, I am a high school student trying to learn C++.

The edited codes, which work :

std::vector<std::string> myVector;
    ifstream myReadFile;
    myReadFile.open("E:/C++/Projects/Textfile project/Textfile project/class_data.txt", ios_base::in); 
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            myReadFile >> output;

            char* token = NULL;
            char* context = NULL;
            char delims[] = " ,\t\n";

            token = strtok_s(output, delims, &context);

            while (token != NULL)
            {
                myVector.push_back(token);
                token = strtok_s(NULL, delims, &context);
            }
        }
    }
    myReadFile.close();

    for (int i = 0; i < myVector.size(); i++) {
        cout << myVector[i] << endl;
    }
有帮助吗?

解决方案

Instead of the vector of objects of type char std::vector<char> myVector; you need to define a vector of objects of type std::string

std::vector<std::string> myVector;

This statement

myVector.push_back(token);

is invalid because you are trying to push a pointer instead of a character.

Also the if statement inside the while loop

while (token != NULL)
{
    if (token != NULL) 
    {
        myVector.push_back(token);
        token = strtok_s(NULL, delims, &context);

    }
}

is superflouos and can be removed

while (token != NULL)
{
    myVector.push_back(token);
    token = strtok_s(NULL, delims, &context);

}

Also take into account that in this loop

    while (!myReadFile.eof()) {
        myReadFile >> output;
    }

object output is always overwritten. You should combine this loop with the loop of splitting output into tokens. Otherwise you are dealing with the last record of the file.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top