如何在C++中从ifstream读取时检测空行
How to detect empty lines while reading from ifstream in C++
当我从文件中读取时,我想检测空行。我试过line.empty()
、line.size()==0
和line==""
,但都不适用
有什么建议吗?
void readFile(const string & fn){
ifstream fichier;
string line;
try{
fichier.open(fn.c_str(),ifstream::in);
while(getline(fichier,line))
{
if(line.empty())// i tried also line=="" and line.size()==0
{
cout<<"empty line!!"<<endl;
}
else{
cout<<"Line:"<<line<<endl;
}
}
fichier.close();
}catch(const string & msg){
if(fichier.is_open()) fichier.close();
cout<<"Error !!";
}
}
您可以这样做:
string buffer;
getline(fichier, buffer, 'n);
if(isEmpty(buffer)){
//do whatever
}
如果你确定你的行是完全空的(即没有空格、制表符或非文本字符),你的isEmpty函数可以是return buffer=="";
如果它更复杂,并且你的换行符可以包含像\t这样的字符,你可以这样做:
bool isEmpty(string buffer){
for (int i = 0; i<buffer.length(); i++{
if (buffer[i] != 't') //add chars you want to exempt here
return false;
}
return true;
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 使用CMake检测支持的C++标准
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- 读取文件时检测到堆栈粉碎
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何检测我是否有要从套接字读取的内容?(c++)
- 如何检测 Boost.PropertyTree 的解析/读取失败
- 如何在C++中从ifstream读取时检测空行
- 在Linux中检测到从pipe/fifo的另一端读取的尝试
- 读取文件时检测到C++中的空行
- 如何在C++中从istream对象读取时检测空行
- Valgrind在简单迭代器类中检测到无效读取错误
- 从istream中读取int,检测溢出
- Valgrind检测strlen中的无效读取