CLang编译程序(Mac)的运行时错误,使用std :: cin读取double类型 [英] Runtime error for CLang compiled program (Mac) reading double type with std::cin
问题描述
我对C ++非常熟悉,并通过使用C ++的编程原理和实践(第二版)的一些例子。我写了以下简单的程序(在文件Main.cpp):
I'm pretty new to C++ and working through some examples of the book "Programming Principles and Practices Using C++" (2nd Edition). I wrote the following simple Program (in file Main.cpp):
#include <iostream>
#include <string>
int main () {
double d = 0;
std::string s = "";
while (std::cin >> d >> s) {
std::cout << "--" << d << " " << s << "\n";
}
std::cout << "FATAL? "<< d << " " << u << "\n";
}
使用CLang( Apple LLVM版本5.1(clang-503.0.40)(基于LLVM 3.4svn)目标:x86_64-apple-darwin13.2.0线程模型:posix
):
clang++ -o Main -std=c++11 -stdlib=libc++ Main.cpp
工作正常,没有任何错误。但是,当我运行程序时,它表现得很奇怪。我测试了以下输入:
works fine without any errors. However, when I run the program it behaves strange. I tested the following input:
123m
这会导致
--123 m
这很好(对于输入 123 m
同样适用)。但输入以下内容:
which is fine (the same holds for entering 123 m
). But, entering the following:
123a
会导致:
FATAL? 0 m
对于大多数其他字符也是如此(例如 b
, c
,...)。输入 123 a
工作正常(输出: - 123 a
)。
The same happens for most other characters (e.g. b
, c
, ...). Entering 123 a
works fine though (output: --123 a
).
另一方面,使用GNU g ++工程。此外,在使用CLang编译相同程序的Linux机器上不会出现这个问题。
Using GNU g++ works on the other hand. Further, the problem does not come up on a Linux machine compiling the same program with CLang.
如前所述,我是C ++的新手,这似乎是一个Mac OS X具体问题。这是Mac CLang实现中的一个错误,或者我在这里做了严重错误的事情:(
As stated before, I'm new to C++ and this seems to be a Mac OS X specific problem. Is this a bug in the Mac CLang implementation or am I doing something seriously wrong here :(?
提前感谢!
推荐答案
std :: basic_istream :: operator>>
调用 std :: num_get :: get
从输入中提取值直到 C ++ 11
,行为 std :: num_get :: get 像
向前, scanf
的C ++ 11 std :: num_get :: get code>最后调用
strto *
函数,它比基于 scanf
的匹配更灵活。在你的例子中, 123 [af]因为所有的输入都被
>> d
消费,所以>> c c c c c>
std::basic_istream::operator>>
calls std::num_get::get
to extract the value from input. Until C++11
, the behaviour of std::num_get::get
was like that of scanf
with the appropriate formatting string. C++11
onwards, std::num_get::get
ends up calling strto*
functions, which have a more flexible matching than the one based on scanf
. In your example, 123[a-f]
get interpreted as hex. Since all the input has been consumed by >>d
, the >>s
part of while(std::cin >> d >> s)
leads to the parse failing.
这篇关于CLang编译程序(Mac)的运行时错误,使用std :: cin读取double类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!