1
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int person;
    cout << "How many person to data: ";
    cin  >> person;

    int x = 0;
    int i = 1;
    string name[person];
    string adress[person];

    while(x < person){
        cout << i << " person data" << endl;
        cout << "Name: ";
        getline(cin, name[x]);
        cout << "Adress: ";
        getline(cin, adress[x]);
        cout << endl;
        x++, i++;
    }

    for(x=0; x<person; x++){
        cout << name[x] << setw(15) << adress[x] << endl;
    }
}

This is my code to store a name and an adress into an array name[] and adress[] And then i use for loop to print their name and adress

This is output image Result

Why is my 1 person data broken? The name and adress is on the same line while my 2nd person data is fine?

Its fine if i use cin >> but i use getline so i can a full name and an adress with the spaces

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268

1 Answers1

0

For starters variable length arrays

string name[person];
string adress[person];

is not a standard C++ feature. Instead use the standard container std::vector<std::string> like

#include <vector>

//...

std::vector<std::string> name( person );
std::vector<std::string> adress( person );

Or instead of two vectors you could declare a vector of objects of the type std::pair<std::string, std::string> like

#include <utility>
#include <vector>

//...

std::vector<std::pair<std::string, std::string>> persons( person );

In this case you should write in the loop like

    //...
    getline(cin, persons[x].first );
    //...
    getline(cin, persons[x].second);

After this input

cin  >> person;

the input stream contains the new line character '\n' that corresponds to the pressed key Enter. You need to remove it before the while loop like

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

To do this you need to include the header <limits>.

Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
  • Also consider aggregating the name and address in to a structure and then making a single `std::vector` of that structure. This usually helps reduce the book-keeping overhead. – user4581301 Sep 16 '20 at 20:17