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

Problem with cin.getline and the buffer

Status
Not open for further replies.

MidnightSky00

Technical User
Feb 8, 2004
1
US
Hi there,

I seem to be having a very simple problem here, but yet I can't figure it out. When I run the following, if someone enters a string that is larger than 20 the program will kick out. I am pretty sure I know why, but yet I don't know how to fix it without just increasing the buffer size, which is not what I want to do, if possible.

It's very simplistic code, and it is embarrassing that I can't resolve this.

Thanks for the help in advance.





#include <iostream.h>

void main()
{


char word1[3][20];
int x;

for (x=0;x<3;x++)
{
cout << &quot;\nEnter a word: &quot;;

cin.getline(word1[x],20);
}
//cin.ignore();


for (x=0;x<3;x++)
{
cout << &quot;\nYour word was &quot; << word1[x] << &quot;\n\n&quot;;
}



}
 
well,there is nothing wrong with the program,but from the declaration of the variable named &quot;word&quot;,it is clear that the maximun length for each word is 20.Otherwise,you will have a buffer overflow.And yes,if you want to have longer words,you'll have to increase the buffer size;
Code:
#include <iostream.h>
#define MAX_SIZE 20

void main()
{
char word1[3][MAX_SIZE];
int x;

for (x=0;x<3;x++)
{
cout << &quot;\nEnter a word: &quot;;

cin.getline(word1[x],MAX_SIZE);
}
//cin.ignore();


for (x=0;x<3;x++)
{
cout << &quot;\nYour word was &quot; << word1[x] << &quot;\n\n&quot;;
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top