2017-08-13 161 views
1

我试图从存储到字符串中的文件开始计算行的开始处的空格' '。 问题是,我不知道如何告诉std::getline()停止时发现任何字符不同于' '在std :: getline()上使用任何字符作为分隔符

std::getline(file_input, string_target, 'Any_character_except_space'); 
+0

你可能正在接近那个问题。我能想到的一个锤子是'std :: regex'。 – user0042

+0

'std :: getline'不会那样做。编写自己的功能,每次阅读一个角色,直到找到符合条件的角色。 –

+0

您可以查找*空格*并计算std :: getline(f,s,'');'读取空字符串的次数。 – Galik

回答

1

不能使用任何字符,除了空间作为分隔符为std::getline(),没有签名允许这样。

你可以做什么,例如:

std::string line; 
std::getline(file_input,line); 
auto pos = std::find_if_not(std::begin(line),std::end(line),[](char c) { 
     return std::isspace(c); 
    // or c == ' ' 
    // or whatever condition you need 
    }); 
size_t space_count = std::distance(std::begin(line),pos); 

这里有一个full example

+1

为什么有条件?如果'pos == std :: end(line)',那么这个字符串完全是空格,而'std :: distance(std :: begin(line),pos)'将返回字符串的长度,这也是在这种情况下,字符串开头的空格数量。 –

+1

@Benjamin看起来你是对的。我心中略有不同的逻辑。 – user0042

相关问题