police123 police123 - 1 month ago 17
C++ Question

c++ string in for loop makes length 0

I have the following code, for some reason when I try to use a

for loop
to declare
string attribs
from
string wholecommand
,
attribs.length()
returns
0
and

When i try:

cout<<attribs;


It outputs nothing.

for(int q=0;q<wholecommand.length();q++){
cout<<atrribs[q];
}


The code above is the only way i can get output. What is wrong with my code and how can I get it to output data without using a for loop?

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

int main(){
string wholecommand="apple";
string atrribs;
for(int a=0;a<wholecommand.length();a++){
atrribs[a]= wholecommand[a];
}

cout<<"Content of Wholecommand: "<<wholecommand<<endl; //returns apple
cout<<"Length of Wholecommand: "<<wholecommand.length()<<endl; //returns 5

cout<<"Content of attributes: "<<atrribs<<endl; ////////contains nothing
cout<<"Length of attributes: "<<atrribs.length()<<endl; ////////returns 0

system("pause");
}

Answer

Put a

atrribs.resize(wholecommand.length());

before the for() loop to get this working properly.
You cannot assign values via std::string indices, where the target string wasn't resized to match them.

Though it's questionable, what's the purpose of your code sample as is at all? You can simply achieve the same with

atrribs = wholecommand;

without that for() loop.