获取线未将所有字符保存到字符串
getline not saving all characters to string
以下程序将目录列表保存到文件中。然后读取文件,并询问用户文件夹名称是否为收藏夹。我的问题是,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:帝国的崛起,当它读到帝国的崛起时
同时从同一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';
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- C++.我想将更改后的特定字符行保存在字符串中
- 为什么签名字符可以保存大于 127 的值?
- 是否可以在 c++ 中将两位数保存在无符号字符中
- Cin 和 getline 无法正确保存非 ascii 字符
- 获取线未将所有字符保存到字符串
- 如何使用 STL C++读取文件和保存连字符
- 键入特殊字符并保存在文件中
- 生成唯一的随机字符并将其保存在数组中
- 将输入保存到字符数组C++
- 无法将 Unicode(希腊语)字符保存到文件中
- 如何保存没有某些字符的字符串
- 如何读取特定的第一个字符并按C++保存数据
- 使用getchar()获取字符并将其保存到每次C 的新行中的文件中
- 在C++中使用字符指针将字符串保存到类属性
- Qt:将QPixmap保存到std::vector<无符号字符>-或者将QByteArray转换为std::
- 如何将二维字符类型数组逐行保存到 c 中的.txt文件中
- 如何在 c++ 中将字节类型的字符数组数据保存到文件中
- 分配字符缓冲区以保存浮点的文本表示形式
- 我的字符数组数组只保存最后输入的行