是否所有 istream 都像 `cin` 一样跳过白色 space?

Are all istreams skipping white space like `cin`?

据我所知,std::cin 跳过所有白色 spaces,所有其他 std::istream 是否也是如此:std::fstreamstd::sstream , std::iostream 个对象,它们是否跳过白色 space?例如,如果要从包含白色 space 分隔值的文件中读取,是否需要按照与指定任何其他输入格式结构相同的顺序指定跳过?

例如,如果您读取格式为 (val1, val2) 的值:

char par1, comma, par2;
double x,y;
is >> par1 >> x >> comma >> y >> par2;
// check if any input
if(!is) return is;
// check for valid input format
if (par1 != '(' || comma != ',' || par2 != ')')

对于白色 space 分隔值,是否需要指定 白色 space 作为格式标记?

int val1;
char whSp= ' '; // or string whSp = " "; 
is >> val1 >> whSp;

默认情况下是,尽管此行为受基数 class std::ios_base 控制。当流通过调用 init 初始化其缓冲区时,它还会设置 skipws 标志(以及其他内容);格式化输入函数(例如 operator>>)使用此标志来确定是否跳过 whitespace。除非稍后直接或通过操纵器修改此标志,否则格式化函数将始终跳过 whitespace.

至于哪些字符被认为是白色的space 这取决于 ctype 在调用函数时流中注入的语言环境的方面,对于默认的 C 语言环境 (和大多数语言环境)这些是 \t, \n, \v, \f, \r 和 space.

As far as I know cin skips all white spaces, is this the case with all the rest: fstream, sstream, iostream, do they skip white space?

所有标准流类型(关于白色 space)的行为是相同的(否则它们将违反 Liskov 替换原则)。

For example, if you want to read from file containing white space separated values, do you need to specify skipping in the same order you specify any other input format structure?

这是正确的做法。您也可以使用 peek and ignore 来跳过字符。

For white space separated values, do you need to specify white space as format marker?

你举的例子不正确。

无论哪种方式,要控制 space 控制策略,请查看 std::skipws and std::noskipws 流操纵器。