Reading data from user
Summary
Source code
C++: reading_data_from_user.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
// prompt user for his/her name
cout << "Enter your name: ";
// read name
cin >> name;
// prompt user for his/her age
cout << "Enter your age: ";
// read age
cin >> age;
// print a message
cout << "Hello " << name << " of age " << age << "." << endl;
return 0;
}
C: reading_data_from_user.c
#include <stdio.h>
int main() {
char name[21];
int age;
/* prompt user for his/her name */
printf("Enter your name: ");
/* read name */
scanf("%20s", name);
/* prompt user for his/her age */
printf("Enter your age: ");
/* read age */
scanf("%d", &age);
/* print a message */
printf("Hello %s of age %d\n", name, age);
return 0;
}
Sample run
C/C++
Enter your name: John
Enter your age: 22
Hello John of age 22.