police123 police123 - 1 year ago 97
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
string wholecommand

When i try:


It outputs nothing.

for(int q=0;q<wholecommand.length();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?

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


Answer Source

Put a


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download