2015-12-11 28 views
0

如何检查从文件扫描的行是否为空或包含非可打印字符?我试过对getline的结果使用strlen(),当有空行时,它等于1,但不可打印的字符会中断此代码。我该如何做得更好?检查一行是否为空或包含非可疑字符

+1

你的意思非打印字符打破strlen()?或者你不知道如何处理非printables? –

+0

'!* line'和'isprint'应该可以做到。 – szczurcio

回答

1

如果如果是C代码,然后可以写相应的功能自己

int isValid(const char *s) 
{ 
    while (*s && !isgraph((unsigned char)*s)) ++s; 

    return *s != '\0'; 
} 

如果它是一个C++代码,并且使用一个字符数组则可以使用下面的方法

#include <algorithm> 
#include <iterator> 
#include <cctype> 
#include <cstring> 

//... 

if (std::all_of(s, s + std::strlen(s), [](char c) { return !std::isgraph(c); })) 
{ 
    std::cout << "Invalid string" << std::endl; 
} 

对于std::string类型的对象,检查将寻找类似

if (std::all_of(s.begin(), s.end(), [](char c) { return !std::isgraph(c); })) 
{ 
    std::cout << "Invalid string" << std::endl; 
}