假设我有以下变量定义,我试图从标准输入中读取值。
int ia = 3;
double da = 0;
std::cin >> ia >> da;
现在我在标准输入中输入以下值,-4.23 -5.01
如果我现在打印 ia
和 da
,da
是 .23 而 ia
是 -4。
为什么 C++ 将 -4.23 拆分为整数部分和浮点部分,换句话说,为什么 .23 保留在输入流中以供后续读取? -4.23 不会简单地被截断为 -4 然后读入 ia
吗?
现在是一个不同的场景,假设我有与上面相同的代码,但这次我将数字 .23
输入到标准输入流(这只是控制台) ia
存储 0(好的,这似乎遵循上述行为)但是 da
这次包含 0?似乎在这种情况下 0.23
被截断并读入为 0,而 .23 没有像上面那样读入 da
。
我无法理解在这些情况下究竟应该发生什么。这里发生了两件不同的事情。
最佳答案
Why did C++ split -4.23 in to integer component and floating point component, in other words why did .23 remain in the input stream for subsequent streams.
您告诉流输入将包含一个整数和一个 double ,并且它尽力将输入解析为您指定的内容。
流开始读取 int
,读取 -4
,当它看到一个点 时意识到它无法继续读取数字。
,然后停在那里。之后,您告诉 C++ 读取一个 double 值。它看到 .23
后跟一个空格,并将其解释为完全合法的 double
值。
suppose I have the same piece of code as above but this time I enter the number .23 in to the standard input stream (which is just the console)
ia
stores 0 (OK this seems to follow the above behavior) but thenda
contains 0 this time
这是因为当您请求整数输入时,流无法将任何内容合法地解析为 ia
。这会将流置于错误状态,这意味着在重置错误标志之前无法进行进一步的输入。
关于c++ - 将原始类型的值从标准输入读入变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085593/