Problem statement:
Given an integer representing the age of a person and four strings representing their first name, last name, and standard, we need to create a structure that stores these details and then print them in a specific format.
Sample Input:
The input consists of five lines. The first line contains an integer representing the age.
The next four lines contain strings representing the first name, last name, and standard of the person.
15
John
Doe
10th
Sample Output:
Print the person's age, followed by their first name, last name, and standard, each on a new line and separated by a space.
15
John Doe
10th
Explanation:
In this example, the input represents a person who is 15 years old, has the first name "John," last name "Doe," and is in the 10th standard. We need to create a structure to store these details and then print them in the specified format.
#include <iostream>
#include <string>
using namespace std;
struct Person {
int age;
string firstName;
string lastName;
string standard;
};
int main() {
Person p;
// Read input
cin >> p.age;
cin.ignore();
getline(cin, p.firstName);
getline(cin, p.lastName);
getline(cin, p.standard);
// Print output
cout << p.age << endl;
cout << p.firstName << " " << p.lastName << endl;
cout << p.standard << endl;
return 0;
}
Code Explanation
Explanation of the Solution:
We start by defining a structure called Person that contains four members: age of type int, firstName, lastName, and standard of type string.
Inside the main() function, we create a variable p of type Person to store the details of the person.
We read the input values and store them in the corresponding members of the p structure using cin and getline(cin, ...).
We read the age using cin >> p.age.
We ignore the newline character left in the input stream using cin.ignore().
We read the first name, last name, and standard using getline(cin, p.firstName), getline(cin, p.lastName), and getline(cin, p.standard), respectively.
Finally, we print the output in the specified format:
We print the age using cout << p.age << endl.
We print the first name, last name, and standard separated by a space using cout << p.firstName << " " << p.lastName << endl.
We print the standard using cout << p.standard << endl.
This solution demonstrates the usage of structs in C++ to create a custom data type to store and manipulate related information.
I hope this solution and explanation are helpful!