2015-12-11 30 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; 
}