c++ - why am i getting false output in string swap program -


`
asked program input 2 string , print respective size first line in output while second line contains concatenation of 2 string , third line of output contains original string after first character of both string have been swapped..below code..everything working except while printing second string printing unnecessary characters because of entire second string not being printed ps: i'm new c++

int main() { string a,b,c;      cin>>a>>b;    int j=a.size();    int k=b.size();    char s[j],p[k];    cout<<a.size()<<" "<<b.size()<<endl;  c=a+b;  cout<<c<<endl; for(int i=0;i<a.size();i++) { s[i]=a[i];  } for(int i=0;i<b.size();i++) { p[i]=b[i];  } char t; t=s[0]; s[0]=p[0]; p[0]=t; cout<<s<<" "; cout<<p; return 0; }` 

input: dlxecxsye bfjoosgukxgywz

output: 9 14 dlxecxsyebfjoosgukxgywz blxecxsye @ dfjoosgukxgywz

desired output: 9 14 dlxecxsyebfjoosgukxgywz blxecxsye dfjoosgukxgywz

your string p of size k, size of input b (14).

in cycle iterate 0 size of input (9), in case smaller size of input b.

when output content of p @ end of code, chars @ indexes 9 13 not set , print undesired place in memory.


Comments