Hello,
Friends,
I am new to Programming.
I write program on dev c++.

#include <iostream>
using namespace std;
int main()
{
char name;
cout<<"Enter your name";
cin>>name;
cout<<"Name"<<name;
return 0;
}

Now when i execute this program and give input Qaisar it displays Qaisar
And if i input full name Muhammad Qaisar Khan it displays Muhammad only so this is my question that whats the problem please help me in this regard.
I will be very thankful to you.
Thanks.
Qaisar Khan.

Recommended Answers

All 3 Replies

Using the input method cin>>name; you only get one word's worth of input. The extraction operator will stop when it encounters whitespace in the input stream (blank, tab, newline).

In order to get your full name, you need to use the getline( ). Also, you need to declare your variable to be big enough to hold the name. You are declaring a char, which holds exactly one character. That your program appears to be working is the cause of many problems - pushing data onto memory not allocated for it.

so, how about:

char name[100];
...
cin.getline( name, 100 );

Many thanks vmanes
I have successfully executed my program but i have not understand the logic what is cin.getline(name, 100 );
how it works ?

cin.getline( array_name, size_of_array, delimiter )

It reads from the input stream (files as well as console), stores to everything (includeing spaces) to the char array. It will stop either when the delimiter (normally the newline, but you can specify any character) is reached or when the array is fill, less one space reserved for a NULL terminator (marking end of string.)

So you might have something like:

char name[100] = "";  //the assignment makes it a valid, empty string
char address[100] = "";

cout << "Enter your name: ";
cin.getline( name, 100 );
cout << "Enter your address: ";
cin.getline( address, 100 );

You can also use getline with C++ string types. The format is a bit different:

string name = "";

cout << "Enter your name: ";
getline( cin, name );

Here, getline( ) is a standalone function, which takes as arguments the input stream (again, console or file) and the name of the destination string. No size limit is needed. Delimiter is again an optional parameter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.