getline не сохраняет все символы в строку - PullRequest
0 голосов
/ 09 июня 2018

Следующая программа сохраняет список каталогов в файл.Затем файл читается и спрашивает пользователя, является ли имя папки избранным или нет.Моя проблема в том, что функция getline не сохраняет все символы входного файла в строку.Вот код:

int main()
{
    fstream list;
    fstream favorites;

    string command1;
    string command2;
    string file;
    string file2;
    string line;

    // Cycle through the directories outputing the list of directories to a file

    for (int i = 0; i < 27; i++)
    {
        system("Y:");
        command2 = "dir Y:\\Blu-Rays\\";
        command2 += letters[i];
        command2 += "\\";
        command2 += " /b > Y:\\Blu-Rays\\";
        command2 += letters[i];
        command2 += "\\files.txt";
        cout << command2 << endl;
        system(command2.c_str());

        file = "Y:\\Blu-Rays\\";
        file += letters[i];
        file += "\\files.txt";
        list.open(file);

        file2 = "Y:\\Blu-Rays\\";
        file2 += "favorites.txt";
        favorites.open(file2);

        // The dir command also lists the file.txt in the file, open the file and erase the line
        while (getline(list, line))
        {
            // If the line file.txt is recognized, do not append the line to the file
            if (line != "file.txt")
            {
                list << line << endl;
                save(line);
                line = "";
            }
        }
    }

    list.close();
    favorites.close();

    return 0;
}

Вот результат из кода:

dir Y:\Blu-Rays\#\ /b > Y:\Blu-Rays\#\files.txt
Current title: 2012
Do you want to save the title as a favorite? [y/n]: y
Current title: s to Kill
Do you want to save the title as a favorite? [y/n]: n
Current title: Rise of an Empire
Do you want to save the title as a favorite? [y/n]: n

Предполагается, что 4-я строка вывода будет 3 дня на убийство и будет читать s дляУбийство.Далее предполагается, что пятая строка гласит: 300: Восстание Империи, когда оно читается как Восстание Империи

1 Ответ

0 голосов
/ 09 июня 2018

Чтение и запись с одного и того же std::fstream одновременно, вероятно, не даст ожидаемого результата.

Более простое решение - использовать boost::filesystem или std::filesystem для перебора файлов:http://en.cppreference.com/w/cpp/experimental/fs

for(auto& path: fs::directory_iterator("y:\\blurays\\"))
        std::cout << path << '\n';
...