My Aim: I am making a Course Management System. Here the query I am sharing is related to the component of the program that adds details about the new degree program user wishes to enter.
Problem: I am using cin.getline() to take the input from the user as it also takes in space which I need to write the complete name of the program for example: Software Engineering. Therefore I cannot use cin >> here.
Terminal Output with Garbage Values
I understand it is because of the fact my array size id 50 and I am entering less characters that is why it is prining out garbage value. How should I solve it
void admin() {
system("CLS");
title();
char wish;
int i(1);
string buffer;
ofstream fbout;
ifstream fbin;
fbout.open("program.txt", ios::out | ios::app| ios::binary);
fbin.open("program.txt", ios::in | ios::binary);
program degree;
if (!fbout) {
cerr << "Error in openning file" << endl;
}
else{
while (fbin.read((char*)°ree, sizeof(degree))) {
cout << i <<". "<< degree.category <<" " <<degree.name <<" (" <<degree.callName << ")" << "" <<degree.school<<endl;
i++;
}
cout << "Enter new program (Y/N)" << endl;
cin >> wish;
if (wish == 'Y') {
cin.ignore(numeric_limits<streamsize>::max(), '
');
cout << "Program Name : "; cin.getline(degree.name,50);
cout << "School Name : "; cin.getline(degree.school,50);
cout << "Degree Type : "; cin.getline(degree.category,50);
cout << "Acronym : "; cin.getline(degree.callName,10);
fbout.write((char*)°ree, sizeof(degree));
fbout.close();
admin();
}
question from:
https://stackoverflow.com/questions/65857427/garbage-value-with-cin-getline 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…