0

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 
?
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    Did you mean `"Small"` (string literal), not `'Small'` (multi-character literal)? – Wyck Dec 07 '22 at 04:18
  • 1
    `'Small'` tells the compiler that you want a character five characters long. You probably want `"Small"`. – user4581301 Dec 07 '22 at 04:18
  • Also, for your sanity, use `std::array R_name;`. – Ben Dec 07 '22 at 04:19
  • 1
    Reasonably close duplicate of [invalid conversion from 'int' to 'const char*'](https://stackoverflow.com/q/9702506/1563833) and probably best explained by [Single quotes vs. double quotes in C or C++](https://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c) – Wyck Dec 07 '22 at 04:23

2 Answers2

0

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".

Wyck
  • 10,311
  • 6
  • 39
  • 60
0
   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.