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
)
- (when you use more than 4 characters, because it typically interprets each character as a byte and is trying to fit it into an
- 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 asint
, so there's overflow.)
- (because it's trying to choose a type to assign to your string, and chooses
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.