#include<bits/stdc++.h>
using namespace std;
//function to check for substring in a string
int check(const char* str,const char* substring)
{
char* pos = strstr(str,substring);
if(pos)
return 1;
else
return 0;
}
int main(){
int t;
cin>>t;
while(t--)
{
char inp [100000];
cout<<"Enter String:";
gets (inp);
int rec,total=-1;
puts(inp);
rec = check(inp,"010");
total = rec;
rec = check(inp,"101");
total = total +rec;
if(total>0)
cout<<"GOOD"<<endl;
if(total==0)
{
cout<<"BAD"<<endl;
}
}
return 0;
}
The function is getting called two times for each iteration call from the while loop.In first iteration of while loop, the call to check() function takes place without inputting inp considering it a null string. In further iterations inp is taken from user and everything starts working properly.
gets
reads a line until new line character \n
is found. Since a new line is still in the input buffer from the previous call to cin>>t
the next call to gets()
will see that new line and return without reading anything. You need to call cin.ignore(INT_MAX,'\n')
after the call to cin>>t
.
cin>>t;
cin.ignore(INT_MAX,'\n');//this will remove everything up to and including a new line character from the input buffer
while(t--)
{
...//your other code
}
And on unrelated note, it would be better if you use getline
to read a line from a stream and std::string
to accept the input instead of a character array(consider what will happen if the user inputs a string of more than 1000 characters):
#include <string>
....
std::string inp;
std::getline(cin,inp);//reads a line
//if you don't want to modify your functions prototypes then you call your check function like
rec = check(inp.c_str(),"010");//string::c_str() will return a c string
but if you don't want to do that at least use fgets()
to specify the maximum number of characters to read from the stream like:
fgets(inp,1000,stdin);//will read at most 999 characters from the input stream