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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about cin.getline()

Status
Not open for further replies.

metamorphy

Programmer
Dec 16, 2001
34
US
Why doesn't this program allow me to input anything into
name? Am I misusing cin.getline()? Is there a more effective way to accomplish what I am trying to do here?

#include <stdio.h>
#include <iostream.h>

struct database{
int integer;
char name[50];
char notes[200];} record[100];


void main()
{
cout << &quot;Enter an integer: &quot;;
cin >> record[1].integer;
cout << &quot;\nEnter a name: &quot;;
cin.getline(record[1].name,sizeof(record[1].name)-1);
cout << &quot;\nEnter some notes: &quot;;
cin.getline(record[1].notes,sizeof(record[1].notes)-1);

cout << &quot;\nRECORD:&quot; << record[1].integer;
cout << &quot;\nNAME:&quot; << record[1].name;
cout << &quot;\nNOTES:&quot; << record[1].notes;
}
 
I don't use stream functions much, but what happens if you try:

cin.getline(record[1].name, sizeof(database.name)-1);
 
I tried your suggestion but I got a compiler error:

syntax error: missing ')' before '.'


Could I also use scanf and printf instead of stream
functions? Which way do you recommend as being the
easiest to use?
 
Sorry for the bad advice. I'm not sure what's wrong, but as a work-around, how about trying this:


char sInput[50] ;
sInput[0] = '\0';

cin.getline(sInput, sizeof(sInput));
strcpy(record[1].name, sInput);


This isn't the cause of your problem, but as a side point, don't forget that indexes in C/C++ are zero based. In other words, the first record would be record[0].name...
 
The problem is not there in the getline. A newline character will be stored in the keyboard buffer after the number input.

The default delimiter for the getline is '\n', so it gets the '\n' for the name.

put a cin.get(); before the getline for the name or change the delimiter of the getline by any other character like
cin.getline(record[1].name,sizeof(record[1].name)-1, '\0');.

You can use any character as a delimiter.

Maniraja S
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top