N
N
newmersedez2020-11-29 21:07:41
C++ / C#
newmersedez, 2020-11-29 21:07:41

Why is the data entered incorrectly in the program?

I want to enter data about a class object until the user wants to finish entering. The first time everything is OK, but during the second input, for some reason, something is written to the first field of the class. Why is that?
Here is the program:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "competitionclass.h"

using namespace std;

int		main()
{
  int					choice = 1;
  Competition			temp_cat;
  vector<Competition> vector;
  cout << "Enter information about cats:" << endl;
  while (choice != 0)
  {
    temp_cat.initCat();
    vector.push_back(temp_cat);
    cout << "Do you want continue?(any num = yes/0 - no)";
    cin >> choice;
    cin.clear();
  }
  cout << endl;
  for (int i = 0; i < vector.size(); i++)
  {
    cout << i << ". Cat info:" << endl;
    vector[i].printCatInfo();
    cout << endl;
  }
  return 0;
}


The input error looks like this (why did he fill in the breed class field?):
Enter information about cats:
Enter breed of cat: maine coon
Enter name of cat: Lucie
Enter color of cat: smoke
Enter mother of cat: Lilly
Enter father of cat: Stan
Enter owner lastname: Ivanov
Enter age: 3
Enter position: 2
Do you want continue?(any num = yes/0 - no)1
Enter breed of cat: Enter name of cat: Koko

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dalp, 2020-11-29
@newmersedez

To enter information in Competition::initCat()you use getline(), which takes the entire input buffer.
When you type choice, you type "1" followed by a newline. While "1" goes from the buffer to the choice variable, '\n' (line feed character) remains in the buffer. It is this character that the function accepts . To solve the problem, you can clean up the line after entering choice using . In this case, you can use . This function will delete characters from the buffer until it encounters a newline character, or until 1000 characters have been deleted. However, this method will not work if the user enters a number + 1000 spaces + '\n', because in this case the translation character will not be removed.getline(cin, breed)
cin.ignore(1000, '\n'), it's better to use cin.ignore(numeric_limits::max(), '\n'). This option will definitely clear the entire line including '\n', but you need to include the library to use it:
#include <limits>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question