Actually, when you are using for loop, it is accessing position in string changing it. Since when you have initialized string as string str = " "
this means our string is of single whitespace. After which for loop access that string and look for the index str[i]
and changes its value to i+'0'
.
So, when we are writing code as
for(int i=0; i< 5; i++){
str[i]=i+'0';
cout<<str[i];
}
it seems, like for that block, str[i] value is i+'0', which is printed, but str doesn't update. Due to which when you do cout<<str;
it again shows 0
as the answer.
To solve this issue we can use property of concatenation, refer the below code
#include <iostream>
using namespace std;
int main()
{
string str;
for(int i=0;i<5;i++)
str+=i+'0';
cout<<str;
return 0;
}
This gives the required result as 01234
.
Hope this helps you.