what is the problem with the code why is string s not printed?

#include
#include
using namespace std;
int main()
{ string s;
string o;
cin>>o;
for(int j=0;j< o.size(); j++)
{
if(o[j]==1)
{s[j]=‘b’;}
else if(o[j]==0)
{s[j]=‘a’;}
}
cout<<s;
return 0;

}

the statement should be if o[j]==‘1’

1 Like

string s is not initialized. it’s empty. try putting “string s = o;” (without quotations) after “cin>>o;” so that you can use the indexing of s in the if conditions.

1 Like

I don’t think you can directly access the indexes in a string like that. Since you are modifying s serially, I would suggest you use:

if(o[j]=='1') 
  {s.push_back('b');} 
else if(o[j]=='0') 
  {s.push_back('a');}
2 Likes