-
a new day a new problem
hi im having a bit of a problem with a gets function
Code:
void store::findF(void)
{
int i = 0;
bool serch = false;
char person[20];
//system("cls");
cout << "please enter the name of the person you wish to find their details : " << endl;
gets (person);
cout << person;
for(i = 0; i < Voters; i++)
{
if(!strcmp(np[i].name, person) )
{
cout << "Eurika" << np[i].name << "\n" << np[i].phone << "\n" << np[i].address << "\n" ;
cout << np[i].email << "\n" << np[i].party ;
serch = true;
}
// cout<<i;
}
if(serch == false)
{
cout << "Sorry record not found.";
}
}
ok ignore any small errors in here the problem i have concerns the gets function
when i call this function the gets returns a null value and therefore prints eurikia and a list of names from my database/list
any help would be most appreciated
-
This is now the third time I've warned you not to use gets. Use fgets. Better yet, use cin.
-
would this work?
cin >> person;
gets(person)
-
-
sorry that works fine the cin i was struggiling because fgets kept giving me an error thanks a bunch
-
Just use std::string and getline().
Nice and safe, and lots of things to help you parse the result.
gets() and short char arrays in C++ - Ugh!!!
-
This works only if the string entered is smaller than the block allocated for person. This is better:
Code:
char person[MAX_SIZE];
cin.getline(person, MAX_SIZE);
This is best:
Code:
string person;
getline(cin, person);
-
Just in case, I'd make person a MAX_SIZE + 1 array, for the \0 character.
-
Actually getline handles the null character correctly if you pass it the array size, so it will read in a maximum of MAX_SIZE - 1 characters.