Code either won't compile, or doesn't work

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.
Last edited on
See this:

http://www.cplusplus.com/reference/string/string/string/

Line 11 should look like this:

const std::string stars(s_name.size(),'*'); // Note: no = and '' instead of ""
Ah, thank you very much. I guess it wasn't exactly per the book as I thought!

Still, it seems odd that with double quotes (though I know that's wrong), even though the output is incorrect, that it does compile.

Anyway, I obviously have much to learn. Thank you again for your help.
Last edited on
The problem is implicit conversion. For example '*' can be implicitly converted to size_t.
This means that the wrong constructor can be called.

The link above shows the constructs std::string provides.
Topic archived. No new replies allowed.