C++ Basic Programming 8

Question:7
C++ program to take input for student details like roll, name and per. Further, display the details?
Sol:

#include <iostream>
using namespace std;
int main()
{
    int roll;
	char name[20];
	float per;
    cout<<"Enter roll no ";
    cin>>roll;
    cout<<"Entre name ";
    cin>>name;
    cout<<"Enter per ";
    cin>>per;
	cout<<"Roll no "<<roll<<endl;
	cout<<"Name "<<name<<endl;
	cout<<"Per "<<per<<endl;
    return 0;
}
/* Output */
Enter roll no 101
Entre name amit
Enter per 98
Roll no 101
Name amit
Per 98

Question:
C++ program to take input for a string and display it?
Sol:

#include <iostream>
using namespace std;
int main()
{
	char n[20];
    cout<<"Enter any string ";
    cin>>n;
	cout<<"String is "<<n<<endl;
    return 0;
}
/* Output 1 */
Enter any string hello
String is hello
/* Output 2 */
Enter any string hello world
String is hello

Limitation of cin:
does not take input for a strig after space.

Solutions are given below

 

gets():(get string)
This function helps us to take input for group of characters(string) including spaces.
Header file: stdio.h

Example:
char n[20];
cout<<”Enter any string “;
gets(n);

#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
	char n[20];
    cout<<"Enter any string ";
    gets(n);
	cout<<"String is "<<n<<endl;
    return 0;
}
/* Output */
Enter any string hello world
String is hello world