Home > Mobile >  populating array of strings a for loop?
populating array of strings a for loop?

Time:12-10

I want to populate an array of strings with the help of for loop and print them

string R_name[3] = {""};

for(int i=0; i<=2; i  ){
    R_name[i] = 'Small';
    cout<<R_name[j]<<" "<< endl;
}

It gives me the error: overflow in implicit constant conversion [-Woverflow] And prints

l
l
l 
?

CodePudding user response:

You have accidentally used a multi-character literal instead of a string literal by using single quotes ' instead of double quotes ".

  • 'Small' : Multi-character literal
  • "Small" : String literal

It's non-standard, but for those compilers that support it, when you assign a multi-character literal like 'Small' to a std::string, even though it's legal, you should still get a multitude of warnings including possibly:

  • character constant too long for its type
    • (when you use more than 4 characters, because it typically interprets each character as a byte and is trying to fit it into an int)
  • overflow in conversion from 'int' to 'char' changes value from 'nnnnnnn' to ''c''
    • (because it's trying to choose a type to assign to your string, and chooses char, which is typically not as large as int, so there's overflow.)

The solution, in your case, is to change 'Small' to "Small".

CodePudding user response:

   string R_name[3] = {""};

for(int i=0; i<=2; i  ){
    R_name[i] = "Small";
    cout<<R_name[i]<<" "<< endl;
}

In this way you can populate array of string and print it.

  • Related