1

I can't get the full output of the name, only the first name is getting printed. And I can't input in Date structure variable that I have created inside the Visitor structure. I am just starting to learn and can't seem to find any problem with it. I ran it on both my system and online C++ compiler.

#include<iostream>
#include <string>

using namespace std;

int main() {

    /* Made a Structure here to store date. */
    struct Date {
        int day, month, year;
    };



    /* A structure to store visitor details. */

    struct Visitor {
        string name;
        Date visitday;   //Structure variable of Date Structure inside Visitor Structure.
    };

    Visitor person;      // Structure Variable of Visitor Structure.

    cout << "Enter Name-";
    cin >> person.name;
    cout << "\nEnter Day- ";
    cin >> person.visitday.day;
    cout << "\nEnter Month- ";
    cin >> person.visitday.month;
    cout << "\nEnter Year- ";
    cin >> person.visitday.year;
    cout << "\nName- " << person.name << " " << "\nDay of Visit- ";
    cout << person.visitday.day << "/" << person.visitday.month << "/" << person.visitday.year;

    return 0;

}
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • That works well, maybe you forgot to add an newline at the end of the last printed line and your console is unable to flush the buffer? – Jean-Baptiste Yunès Jan 29 '23 at 09:40
  • @Mohammad Aslam The operator >> enters only on word. To enter several words in an object of the type std::string use function getline. – Vlad from Moscow Jan 29 '23 at 09:44
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – JaMiT Jan 29 '23 at 10:06

1 Answers1

1

When you use:

std::cin >> person.name;

The parser parses only one word, i.e. treats the space(s) (' ') as a separator.

You can use std::getline instead:

std::getline(cin, person.name);

This will fill person.name with the complete string you enter, till the first newline.

A side note: Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39