A little bit of background - I'm new to learning C++. I'm working through Accelerated C++ and following things along. In chapter 4, the code I've got doesn't quite work as the book suggests, and I've double-checked all my of code to make sure I'm not mis-typing something from their example (I can't see any errors, anyway).
I have the following struct and two functions:
struct Student {
std::string name;
double midtermGrade, finalGrade;
std::vector<double>homework;
};
std::istream& read(std::istream& is, Student& s) {
is >> s.name >> s.midtermGrade >> s.finalGrade;
std::cout << std::endl << "Name: " << s.name << std::endl
<< " - Md: " << s.midtermGrade << std::endl
<< " - Fn: " << s.finalGrade << std::endl;
read_hw(is, s.homework);
return is;
}
std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
if (in) {
hw.clear();
double h;
while (in >> h) {
std::cout << " - Hw: " << h << std::endl;
hw.push_back(h);
}
in.clear();
}
return in;
}
In int main()
I'm calling that code like this:
Student record;
while (read(std::cin, record)) {
If I compile and run, then paste (or type) in the following input, I get the following output:
// Input
Johnny 70 80 50 Fred 95 90 100 Joe 40 40 50
// Output
Name: Johnny
- Md: 70
- Fn: 80
- Hw: 50
Name: red
- Md: 95
- Fn: 90
- Hw: 100
Name: Joe
- Md: 40
- Fn: 40
- Hw: 50
As you can see, "Fred" has become "red". I've tried this with a whole bunch of names; anything starting with A-F is affected by the same issue, which caused me to suspect it may be a hexadecimal issue. However, "Nick" becomes "k" and "Xander" simply becomes "r".
I'm utterly baffled. Do you have any idea what's going on?
As requested, here's a MCVE:
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct Student {
std::string name;
double midtermGrade, finalGrade;
std::vector<double>homework;
};
std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
if (in) {
hw.clear();
double h;
while (in >> h) {
std::cout << " - Hw: " << h << std::endl;
hw.push_back(h);
}
in.clear();
}
return in;
}
std::istream& read(std::istream& is, Student& s) {
is >> s.name >> s.midtermGrade >> s.finalGrade;
std::cout << std::endl << "Name: " << s.name << std::endl
<< " - Md: " << s.midtermGrade << std::endl
<< " - Fn: " << s.finalGrade << std::endl;
read_hw(is, s.homework);
return is;
}
int main()
{
Student record;
std::vector<Student> students;
while (read(std::cin, record)) {}
return 0;
}