0

Why is the size of the temp string 0 even after running the loop to copy characters from s? I get 0 as the size of the temp string.

#include <iostream>
#include<string>
using namespace std;

string CopyString(string s,int delta,int len){
   string temp;
    int i;
    for (i = 0; i < len; i++)
    {
        temp[i] = s[i + delta];
    }

    cout<<temp.size(); 
    return temp;
}

int main() {
     string s = "Hello";
     cout<<CopyString(s,2,5);
}

1 Answers1

0

It looks like you are trying to create a substring from an existing string. You could always use substr. It takes two arguments, first argument specifies starting index and second argument specifies how many characters to copy.

string s = "Hello";
std::cout << s.substr(2,3) << std::endl;
MasterJEET
  • 349
  • 3
  • 14