In the code below, how is the value of string b changing? Check in the output. The string b should contain value "you what?" for the input I give, but its value changes suddenly in between.
I have not given the main code I was trying to implement because the problem lies here.
/*Program to find no. of Substrings of a type*/
#include<iostream>
#include<string.h>
#include<fstream> /*using fstream to post the output here*/
usingnamespace std;
int main()
{
char a[100];
int i=0,j=0;
cin.getline(a,100);/*the input string*/
char s2[]="you"; /*the substring*/
char *b=strstr(a,s2);
ofstream fout;
fout.open("file.txt");
fout<<b<<endl<<endl;
while(b[j]!='\0')
{
fout<<b<<endl;
fout<<a<<endl<<endl;
a[j]=b[j];
fout<<"Change\n"<<a[j]<<" "<<b[j]<<"\n\n"; /*Why and how is string 'b' chnging?*/
j++;
}
/*Hidden the actual code I was trying to implement because the problem is above*/
return 0;
}
INPUT: hey you what?
you what?
you what?
hey you what?
Change
y y
you what?
yey you what?
Change
o o
you what?
yoy you what?
Change
u u
you what?
you you what?
Change
you what?
you you what?
Change
w w
wou what?
you wou what?
Change
h h
whu what?
you whu what?
Change
a a
wha what?
you wha what?
Change
t t
whatwhat?
you whatwhat?
Change
? ?
No, strstr() function returns a pointer to the first encountered substring in a. And then you assign it to b, so it points inside a now.
Morale: do not use c-strings in c++ if you does not know exatcly what are they and how do they behave.