I'm working through Accelerated C++, and I'm compiling and testing the grading program from chapter 4. For some reason, cin is not able to properly read names that start with certain characters. For example:
$ echo "zach 1 1 1 fred 2 2 2 albert 3 3 3 james 4 4 4 adam 5 5 5" | ./main
james 4
lbert 3
m 5
red 2
zach 1
You can see that names starting with an A or an F will get misread, and at least one character will be cut off from the front.
After I saw this bug in my code, I copied from someone who's posted solutions to every single problem online, and I'm still seeing the bug. Printing to the console shows that the names are being read in like that. I'm really baffled by this, and cannot think of any explanation as to why this is happening.
Also, this is exclusive to Mac. I compiled and ran this on my Windows machine and it returned the correct output. Then I tried it on my other Mac and got the incorrect output again.
Here's an MRE version of the program in question that follows the patterns given in the book and shows similar behavior:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::string;
using std::vector;
double sum_vec(vector<double> &vec)
{
double total = 0;
for (vector<double>::size_type i = 0; i < vec.size(); i++)
{
total += vec[i];
}
return total;
}
istream &read_nums(istream &in, vector<double> &vec)
{
if (in)
{
vec.clear();
double x;
while (in >> x)
vec.push_back(x);
in.clear();
}
return in;
}
istream &read(istream &in)
{
string s;
in >> s;
vector<double> vec;
read_nums(in, vec);
double total = sum_vec(vec);
cout << s << " " << total << endl;
return in;
}
int main()
{
while (read(cin))
{
}
}
After compiling as test you can see the following:
$ echo "albert 1 bruce 2 chris 3 dan 4 edward 5 fanny 6" | ./test
albert 1
ruce 2
hris 3
4 0
ward 5
y 6
0
Compiled by running
g++ -o test test.cpp
Running g++ --version returns:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin