I am student of class 12 and quite new to programming. I have a confusion. The below program works well when I compile it using Borland compiler. But when I compile it using GCC 4.9.2 compiler, it shows one position more than the actual position. I tried to figure it out and have found that it works well if I add the cin.get() (line 16) statement. I think the reason my program was not working was because when I pressed carriage return after inputting size that remained in stream and was extracted when the gets(arr[i]) (line 20) was executed the first time. As a result I got one position more than the actual.
Am I thinking right? Kindly help.
// PROGRAM TO FIND A NAME FROM A LIST OF NAMES USING BINARY SEARCH METHOD
#include <iostream>
#include <stdio.h>
#include <string.h>
usingnamespace std;
int findname(char [], char [][30], int);
int main()
{
char name[30][30];
int size;
cout<<"\nEnter the number of names you want to enter (MAX 30)\n";
cin>>size;
cout<<"\nInput the names in lexicographic order\n";
cin.get();
for(int i =0; i<size; i++)
{
gets(name[i]);
}
char item[30];
cout<<"\nEnter the name you want to search\n";
gets(item);
int pos = -1;
pos = findname(item, name, size); // I have omitted the definition as the function works well
if(pos == -1)
cout<<"\nSearch unsuccessful. Name not found\n";
else
cout<<"\nName found at position "<<pos+1; // I have returned the index in pos so pos+1
return 0;
}
> I think the reason my program was not working was because when I pressed carriage return after inputting size
> that remained in stream and was extracted when the gets(arr[i]) (line 20) was executed the first time.
> As a result I got one position more than the actual.
Now that that has been cleared, it is time to look at another thing that needs to be fixed in the code: gets()
std::gets() (C++)
The function provides no means to prevent buffer overflow of the destination array, given sufficiently long input string. std::gets was deprecated in C++11 and removed from C++14. http://en.cppreference.com/w/cpp/io/c/gets
gets() (C)
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.