gpt4 book ai didi

c++ - 如何测试一行是否为空?

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:01 25 4
gpt4 key购买 nike

我实际上是想了解 getline() 函数是如何工作的!但是我在测试一行是否为空时遇到了困难!

这是我的代码:

ifstream fichier("upload.txt",ios::binary);
string ligne;
while(getline(fichier,ligne))
{
cout<<ligne<<endl;
if(ligne=="")
cout<<"line below is empty"<<endl;
}

但是,if 条件似乎不起作用 :((

最佳答案

在 Windows 上,换行符通常是 CRLF (0x0D 0x0A)。 std::getline() 将读取直到遇到 LF 并将其从返回的 std::string 中丢弃。如果 std::ifstream 以文本模式(默认模式)打开,平台换行符将规范化为 LF 并且前导 CR 也将被丢弃。但是,如果以二进制模式打开,CR 将不会被丢弃。所以你必须检查一下:

ifstream fichier("upload.txt", ios::binary);
string ligne;
while (getline(fichier, ligne)) {
if (ligne.empty() || ligne == "\r") {
cout << "line is empty" << endl;
} else {
cout << ligne << endl;
}
}

否则,不要对文本文件使用二进制模式:

ifstream fichier("upload.txt");
string ligne;
while (getline(fichier, ligne)) {
if (ligne.empty()) {
cout << "line is empty" << endl;
} else {
cout << ligne << endl;
}
}

关于c++ - 如何测试一行是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com