I am having a difficult time understanding what I am doing wrong here. Basically, I am inputting 2 numbers, and then 2 strings. Problem is that when I press enter after the 2nd number, the next (1st) string is empty and literally skipped. It's this particular part of the code:
void garageInput(Garage* gar)
{
cin >> gar->width >> gar->lenght;
getline(cin, gar->location);
//testing the input string
cout << "This is input string: " << gar->location << endl;
getline(cin,gar->automatic);
//testing the input string
cout << "This is input string: " << gar->automatic << endl;
}
My input and output looks something like this:
Enter the number of garages: 1
Type about size, location and other info for 1. garage:
20 20
This is input string:
Renato
This is input string: Renato
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <string>
using namespace std;
class Object
{
public:
string name;
int value;
};
class Garage
{
public:
int width, lenght;
string location;
string automatic;
Object obj;
};
void garageInput(Garage* gar)
{
cin >> gar->width >> gar->lenght;
getline(cin, gar->location);
//testing the input string
cout << "This is input string: " << gar->location << endl;
getline(cin,gar->automatic);
//testing the input string
cout << "This is input string: " << gar->automatic << endl;
}
void garageOutput(Garage* gar)
{
//printing the location of the garage and its dimensions with object in it
cout << gar->location << " " << gar->lenght << "x" << gar->width << " - " << "objects:";
cout << gar->obj.name << " " << gar->obj.value << endl;
}
int main()
{
cout << "Enter the number of garages: ";
int n;
cin >> n;
Garage* gar = new Garage[n];
for (int i = 0; i < n; i++)
{
cout << "Type about size, location and other info for " << i + 1 << ". garage: " << endl;
garageInput(&gar[i]);
}
int m;
cout << "Enter the number of objects: ";
cin >> m;
int k;
for (int i = 0; i < m; i++)
{
//each garage can only have 1 object
cout << "Enter the number of garage which this object belongs to- No. " << i + 1 << "";
cin >> k;
cout << "Enter the name and value of object: ";
cin >> gar[k - 1].obj.name >> gar[k - 1].obj.value;
}
cout << "Info: " << endl;
for (int i = 0; i < n; i++)
{
cout << i + 1 << " ";
garageOutput(&gar[i]);
}
}
My guess is that using the getline automatically takes the '\n' from the buffer or something similar. I am confused about this bc I just started programming in C++ from C where I would use
scanf("%[^\n]\n",string);
I tried using
cin>>gar->width>>gar->length;
cin>>gar->location;
cin>>gar->automatic;
But it divides the location line (for example New York) into location and automatic(each word for each value while it all should be in the location value as string). Thank you!