Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ getline未将所有字符保存为字符串_C++_String_Getline - Fatal编程技术网

C++ getline未将所有字符保存为字符串

C++ getline未将所有字符保存为字符串,c++,string,getline,C++,String,Getline,以下程序将目录列表保存到文件中。然后读取文件并询问用户文件夹名称是否为收藏夹。我的问题是,getline函数没有将输入文件中的所有字符保存为字符串。 代码如下: int main() { fstream list; fstream favorites; string command1; string command2; string file; string file2; string line; // Cycle throug

以下程序将目录列表保存到文件中。然后读取文件并询问用户文件夹名称是否为收藏夹。我的问题是,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 to Kill。接下来,第五行应该是:300:帝国的崛起当它读到帝国的崛起时

同时从同一个
std::fstream
读和写可能不会做你期望的事情

更简单的解决方案是使用
boost::filesystem
std::filesystem
迭代文件:

for(自动路径:fs::目录迭代器(“y:\\blurays\\”)

std::无法编辑您的问题以包含a。此外,英文字母表有26个字母,而不是27个。您正在向读取的同一个文件写入。为什么要使用
system()
来使用单独的命令进程枚举文件系统,而不是使用类似
boost::filesystem
file(First | Next)file()的内容
在Windows等上直接用自己的代码枚举文件?那么您根本不需要输入文件,因为您已经在内存中有了文件名。
for(auto& path: fs::directory_iterator("y:\\blurays\\"))
        std::cout << path << '\n';