Hi, i don't understand how
cin and
cin.getline work exactly. I had problem with cin, which was solved here
http://www.cplusplus.com/forum/beginner/88267/ , but still noone explained me how it works exactly. Today i stepped into another problem. I was writing a
strstr function that scans one string for another string. It looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int m_strstr(char* base, char*targ)
{
char* targbuf = targ,* basebuf = base;
while (*base)
{
if (*base==*targ)
targ++;
else
targ=targbuf;
if (!(*targ))
return (int(base) - int(basebuf));
else
base++;
}
return -1;
}
|
It works perfectly no matter what. The problem is in mother-function of
strstr in which user is asked to type base and targ strings. It looks like:
1 2 3 4 5 6 7 8
|
char l1[40]={' '}, l2[40]={' '};
cout << "Gimma string to scan, yo! ";
cin.getline(l1,10);
cout << "Na gimma string dat i look 4. ";
cin.getline(l2,30);
int bit = m_strstr(l1,l2);
cout << "Stry' pos': " << bit;
getch();
|
It also works great assuming that l1 has no spaces inside. If it has, second cin.getline is ignored and output looks like that:
Gimma string to scan, yo! Chickens ain't bad
Na gimma string dat i look 4.
Stry' pos': 0 |
And everytime i run it again (during one stand of program) it looks just like:
Gimma string to scan, yo!
Na gimma string dat i look 4.
Stry' pos': -1 |
.
I have already figured out that it is not because of spaces, it's because of the fact that second argument of
cin.getline is smaller than length of string i typed here. But still, why does it behave so strangely?