Hi. I'm trying to do some exercises from a book, and can do most of them okay. However, with this one I've tried a couple of different things but it doesn't work, in respect of the fact that even though it compiles, I only ever get one asterisk in the stars variable, no matter how long the s_name variable is. However, I know that s_name.size() works, since it'll happily spit out the length of it further down.
Still, as one can see, this is using "*" with double quotes, and not the single quotes which I thought it should do. With single quotes, however, it won't compile at all, and I'll get the message given below the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
int main()
{
std::string s_name;
std::cout << "Enter your name: ";
std::cin >> s_name;
const std::string stars=(s_name.size(),"*");
std::cout << stars << std::endl;
std::cout << s_name << std::endl;
std::cout << stars << std::endl;
std::cout << "The size of " << s_name << " is " << s_name.size() << " bytes." << endl;
return 0;
}
|
1 2
|
error: conversion from ‘char’ to non-scalar type ‘const string {aka const std::basic_string<char>}’ requested
const std::string stars=(s_name.size(),'*');
|
If I replace stars=(s_name.size(),'*') with stars=(10,'*') it also won't compile, and I'll get the same error message:
1 2
|
error: conversion from ‘char’ to non-scalar type ‘const string {aka const std::basic_string<char>}’ requested
const std::string stars=(10,'*');
|
So, I'm very curious why this won't work properly; my understanding is that I should be using single quotes, but that both string.size(), or an integer, should be valid arguments to populate the stars variable with the requisite number of asterisks.
The "const" line is as per the exercise in the book.
Thanks for any assistance.