Input method

Dear Sir,

Consider the following code:

The length of array is four and if I want to give only three character input then after pressing Enter key input doesnot stop. I must input 4 characters. Sir, Please tell me ay other way of taking input because I want it to terminate when Enter key is pressed.

main()
{
char abc[4]={0};

cout<<"Enter you text";
for (int i=0; i<4; i++)
{

cin>>abc[i];
}
system("cls");
for (int i=0; i<4; i++)
{

cout<<abc[i]<<endl;
}
getche();
}
You need to check if the entered character is the ENTER key. I don't think you can do this with cin::operator>>(), so you need to use cin.get():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main(){
	char abc[4]={0};
	cout<<"Enter your text:\n";
	for(int i=0;i<4;i++){
		abc[i]=cin.get();
		if(abc[i]=='\n'){
			break;}}
	system("cls");
	for(int i=0;i<4;i++){
		if(abc[i]!='\n'){
			cout<<abc[i]<<endl;}}
	getchar();}

Once you set abc[i] to the character, you check if it's the enter key (\n), and if it is you break out of the for loop. Then when you're outputting it, you only output it if abc[i] isn't the ENTER key.
Last edited on
Why not just use the istream::getline() method?
http://www.cplusplus.com/reference/iostream/istream/getline/

cin.getline( abc, 4 );
Topic archived. No new replies allowed.