Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Chararcter output

Status
Not open for further replies.

teser

Technical User
Mar 6, 2001
194
US
Please advise why I only get the first letter from my string entry.

Here is my output:

Enter name: test this
Enter number: 23

Name = t
Emp number = 23

************************

Here is my program:
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#include <iomanip.h>

#define FFLUSH while(cin.get() != '\n')

void getData(char[],int);

void main()
{
char name[20];
int emp;

getData(name,emp);
}

void getData(char name[],int emp)
{
cout << &quot;Enter name: &quot;;
cin.get(name, sizeof(name));
FFLUSH;

cout << &quot;Enter number: &quot;;
cin >> emp;

cout << &quot;\nName = &quot; << name << &quot;\n&quot;
<< &quot;Emp number = &quot; << emp << endl;

}




 
Zyrenthian,

I tried the cin.getline such as:
cin.getline(name,sizeof(name));

and still got same results. Any other suggestions??
 
sizeof(name) will return 1. Pass the actual size of &quot;name&quot; into the function and see what happens. The reason this happens is because sizeof does not know how much memory was allocated unless &quot;name&quot; was declared within the same { } that sizeof is called

for a test right now, try

cin.getline(name,20);

This should produce the desired result.

Matt
 
Thanks,

I am curious to know why I need to enter the character length twice in this program?

char name[20];

cin.getline(name,20);
 
What happens is char name[20] is declared in the main. When you pass name to the function getData(char name[], int emp), the programs knowledge of how large name is is lost until you return to where name was actually declared. However, if there are no spaces in the input for the name i would suggest possibly using cin>>name; That way, as long as the input is no more then 20 characters it will be read in properly.

An alternative is to declare a global constant

const int NAME_LENGTH = 20;

in the main you would declare name as

char name[NAME_LENGTH];

and when the getline is called you
cin.getline(name,NAME_LENGTH);

Matt

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top