问题
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";
}
Compiling the program (on the command line) with CLang (Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.2.0 Thread model: 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
which results in
--123 m
which is fine (the same holds for entering 123 m
). But, entering the following:
123a
results in:
FATAL? 0 m
The same happens for most other characters (e.g. b
, c
, ...). Entering 123 a
works fine though (output: --123 a
).
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.
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 :(?
Thanks in advance!
回答1:
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.
回答2:
Ok, I found a solution to the problem in this question asked: CGAL: How can I successfully compile and link CGAL examples (on Mac OS X 10.9 Mavericks)
Compiling with clang++
as follows:
clang++ -o Main -std=c++11 -stdlib=libstdc++ Main.cpp
instead of:
clang++ -o Main -std=c++11 -stdlib=libc++ Main.cpp
solved the problem.
Anyway, as libc++
should be the preferred library to use with clang++
(as I just was told offline) I think it's time for a bug report.
来源:https://stackoverflow.com/questions/24487481/runtime-error-for-clang-compiled-program-mac-reading-double-type-with-stdcin