[英]Why my string value store all char arrays from my struct?
I reading a file with this data:我用这些数据读取一个文件:
0001 Howard Paredes Zegarra Computacion
0002 Penny Vargas Cordero Industrial
0003 Sheldon Cooper Quizpe Mecatronica
my cpp file is this:我的 cpp 文件是这样的:
struct Alumno {
char codigo[5];
char nombre[12];
char apellidos[20];
char carrera[15];
};
istream& operator >> (istream &stream, Alumno &record)
{ stream.read(record.codigo, 5);
stream.read(record.nombre, 12);
stream.read(record.apellidos, 20);
stream.read(record.carrera, 15);
stream.get();
return (stream);
}
vector<Alumno> load() {
ifstream file("datos.txt");
vector<Alumno> students;
while (!file.eof()) {
Alumno student = Alumno();
file >> student;
students.push_back(student);
}
file.close();
return (students);
}
int main() {
auto students = load();
for (auto student : students) {
string nombre = student.nombre;
cout << nombre << endl;
}
return (0);
}
so the problem is when print the variable "nombre" is printing the whole line less the first column.所以问题是当打印变量“nombre”时打印整行减去第一列。 The expected output:预期的 output:
Howard
Penny
Sheldon
But the current output is:但是现在的output是:
Howard Paredes Zegarra Computacion
Penny Vargas Cordero Industrial
Sheldon Cooper Quizpe Mecatronica
why i am having this output, is this has some problem with pointer char from my struct, any advice would be wonderful.为什么我有这个 output,这是我的结构中的指针字符有问题吗,任何建议都会很棒。 Thanks in advance.提前致谢。 Note: I can not use string for this task.注意:我不能在这个任务中使用字符串。
Since you're using C-style string, you need to add a null-terminator after the char
s you stick in your array.由于您使用的是 C 风格的字符串,因此您需要在插入数组的char
之后添加一个空终止符。 This means you need to increase the size of each char
array by one.这意味着您需要将每个char
数组的大小增加一。 Otherwise when you output, it will keep displaying characters of all the arrays after the array you tell it to print.否则当你 output 时,它会在你告诉它打印的数组之后继续显示所有 arrays 的字符。
Since you are not allowed to use std::string
, append a null terminator (numeric 0
or character '\0'
) to the end of your C-style strings.由于不允许使用std::string
,因此 append 和 null 终止符(数字0
或字符'\0'
)到 C 样式字符串的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.