注意:请在回答之前阅读评论。这个问题似乎是编译器特定的。为什么iostream会在某些字中切断第一个字母?
我有一个简单的程序读取一个名称,并从文件或控制台到一个struct Student_info一些成绩,然后通过重载< <和>>运算打印出的一些数据。然而,该计划正在切断部分甚至整个单词并转移数据。例如,输入
Eunice 29 87 42 33 18 13
Mary 71 24 3 96 70 14
Carl 61 12 10 44 82 36
Debbie 25 42 53 63 34 95
返回
Eunice: 42 33 18 13
Mary: 3 96 70 14
rl: 10 44 82 36
25: 63 34 95
表明不知何故,流已经忽略卡尔的前两个字母,然后转移整个流离开1个字。我一直试图在一个小时内调试它,但似乎是任意的。对于不同的名字,不同的单词被切断,没有明显的模式。
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct Student_info {
friend std::ostream &operator<<(std::ostream &output,
const Student_info &S) { // overloads operator to print name and grades
output << S.name << ": ";
for (auto it = S.homework.begin(); it != S.homework.end(); ++it)
std::cout << *it << ' ';
return output;
}
friend std::istream &operator>>(std::istream &input, Student_info &S) { // overloads operator to read into Student_info object
input >> S.name >> S.midterm >> S.final;
double x;
if (input) {
S.homework.clear();
while (input >> x) {
S.homework.push_back(x);
}
input.clear();
}
return input;
}
std::string name; // student name
double midterm, final; // student exam scores
std::vector<double> homework; // student homework total score (mean or median)
};
int main() {
//std::ifstream myfile ("/Users/.../Documents/C++/example_short.txt");
Student_info student; // temp object for receiving data from istream
std::vector<Student_info> student_list; // list of students and their test grades
while (std::cin >> student) { // or myfile >> student
student_list.push_back(student);
student.homework.clear();
}
for (auto it = student_list.begin(); it != student_list.end(); ++it) {
std::cout << *it << '\n';
}
return 0;
}
编辑:添加换行符。
用'getline()'将整行读入一个字符串,然后使用'std :: stringstream'将其读入结构成员。 – Barmar
它在我的电脑上运行得非常好。 – Jiahao
@ArnoldLayne Odd。我在XCode 8.3.3中编译,[this](http://imgur.com/a/bxNvU)是输出。 – JAustin