字符提取与字符串提取有何不同?

字符提取与字符串提取有何不同?

问题描述:

使用字符和字符串禁用空白跳过时,行为是不同的。似乎提取整个字符串(包括空白字符)的唯一方法是使用字符和noskipws。但是对于字符串来说这是不可能的,因为它不会在第一个空格之后提取。字符提取与字符串提取有何不同?

std::string test = "a b c"; 
char c; 
std::istringstream iss(test); 
iss.unsetf(std::ios_base::skipws); 
while (iss >> c) 
    std::cout << c; 

将输出a b c但变化℃至弦和它只输出a

+1

http://stackoverflow.com/questions/21820867/why-does-stdoperatoristream-char-extract-whitespace – 0x499602D2 2014-10-02 18:06:10

>>运算符为一个字符串提取单词,并在 停止在它看到的第一个空格。如果它不跳过初始白色 空间,则它立即停止,并返回一个空字符串。

你不说你想如何分隔字符串。要阅读 直到行尾,只需使用std::getline。要读取直到 文件的末尾,你可以使用类似:

std::istringstream collector; 
collector << iss.rdbuf(); 
std::string results = collector.str(); 

这不是最有效的,但如果该文件是小,它会 做。