why this c++ code gives such output? -
#include<bits/stdc++.h> using namespace std; string str ; string str ; int main(){ for(int i=0;i<6;i++) /// 012345 str[i] = + '0' ; for(int j=0;j<6;j++) /// abcdef str[j] = j + 'a' ; cout << str << " " << str << endl ; /// blank line !!! printf("%s\n",str.c_str()); /// abcdef printf("%s\n",str.c_str()); /// abcdef return 0; }
output ::
abcdef abcdef
i expect ::
012345 abcdef 012345 abcdef
you have undefined behavior!
the strings declare empty, , indexing of them out of bounds.
instead should append characters string, either using append
member function or +=
operator.
Comments
Post a Comment