mardi 22 mars 2022

Getting garbage values when printing a string character by character

So, I was trying to code a problem and It required me to copy a string from certain index to another string.

After an hour of debugging, I found that my string was actually consisting of garbage values.

Can anyone explain why? I have been using this approach forever and It's the first time I faced this issue.

Original Problem is unrelated to this question so I am just sharing my approach.

My approach was :

#include<bits/stdc++.h>
using namespace std;

int main(){

   string s;
   cin>>s;

   int idx;
   cin>>idx;

   string ans;

   for(int i=idx;i<ans.length();i++){
       ans+=s[i];
   }

   cout<<ans<<endl;

}

Input:
   ()(()
   1
    

Output:
   0d0a 290d 0a28 2828

Aucun commentaire:

Enregistrer un commentaire