Runtime error for a compiled CLAN program (Mac) that reads a double type with std :: cin

I am new to C ++ and am working on some examples of the book "Principles and Practices of Programming Using C ++" (2nd edition). I wrote the following simple Program (in the Main.cpp file):

#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) using 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 errors. However, when I run the program, it behaves strangely. I tested the following input:

 123m 

that leads to

 --123 m 

which is excellent (this is also true for entering 123 m ). But by entering the following:

 123a 

leads to:

 FATAL? 0 m 

The same thing happens for most other characters (e.g. b , c , ...). Entering 123 a works fine (output: --123 a ).

Using GNU g ++ works, on the other hand. Also, the problem does not occur on a Linux machine compiling the same program with CLang.

As already mentioned, I am new to C ++ and this seems to be a Mac OS X problem. Is this a bug in the implementation of the Mac CLang or am I doing something seriously wrong here: (?

Thanks in advance!

+2
source share
2 answers

std::basic_istream::operator>> calls std::num_get::get to std::num_get::get value from the input. Prior to C++11 behavior of std::num_get::get was similar to scanf with the corresponding format string . C++11 onwards std::num_get::get ends with a call to strto* functions that have a more flexible correspondence than that based on scanf . In your example, 123[af] interpreted as hex. Since the entire input was consumed >>d , part >>s while(std::cin >> d >> s) causes the parsing to fail.

0
source

Ok, I found a solution to the problem in this question: 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:

clang++ -o Main -std=c++11 -stdlib=libc++ Main.cpp

solved a problem.

In any case, since libc++ should be the preferred library to use with clang++ (since I was just told offline), I think this is the time to report the error.

0
source

Source: https://habr.com/ru/post/972073/


All Articles