jeudi 2 juillet 2015

Programming Principles C++ Stroustrup book, Ch.4 -- Mac G++ compiler acts strangely

#include "book.h"

// Test input of numbers with suffixes, e.g. 10cm, 4.56m.

int main()
{
    double num;
    string suffix;

    cout << "Try it: ";
    cin >> num >> suffix;
    cout << num << " " << suffix << endl;

    return 0;
}

This is a small piece of code that I have written to attempt to pinpoint a strange behavior that I ran into while working through Chapter 4 of the Stroustrup C++ Programming Principles book. The include statement includes the header file that accompanies the book (std_lib_facilities.h), which I renamed because quite frankly I got tired of typing that mouthful umpteen times as I worked my way through the exercises. I am compiling my code on a Mac OS X (10.9.5), using the g++ compiler with only the -std=c++11 flag (g++ -std=c++11 ).

Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

That is the last three lines of what I get when I type "g++ --version" into the Terminal.


On my computer, with my compiler, for reasons that I cannot decipher, this program only functions properly with certain string input. I will run the program now as I am typing this question and record the behavior:

Try it: 58z  
58 z

Try it: 58zoltan 
58 zoltan

Try it: 58.954zoltan
58.954 zoltan

All good so far...

Try it: 58a
0

Try it: 58 a
58 a

Try it: 58b
0

...proceeding alphabetically.

Non-bold letters return 0, bold letters return correct results: abcdefghijklmnopqrstuvwxyz. As in, 58g returns 58 g, but 58i returns 0...for the entire alphabet.

  • Testing with uppercase letters reveals the exact same pattern of failure.

  • Any word that starts with a "forbidden" letter will also make the program return 0 (58images returns 0 as well as 58i).

  • A number with a decimal portion (e.g. 58.934) paired with a forbidden letter behaves the same as an integer.


This question may have been asked before, but it doesn't seem to have been answered before. I tried the ##c++ IRC chatroom on freenode, and everyone there who ran this snippet reported successful performance across the entire alphabet. I took this code to wandbox, where it performed successfully. Every answer and comment I saw in the linked stackoverflow question reported successful performance, no problems with the code.

And yet...it will not run properly on my machine. Not only does it not run properly, but the pattern of failure makes absolutely no sense to me. I guess my question is: what in the heck is going on with this code? My only guess is that the nonfunctioning letters are being interpreted as some sort of type-casting signifier.

Aucun commentaire:

Enregistrer un commentaire