invalid conversion from ‘const char*’ to ‘char’
I'm trying to compile the following example from Koenig/Moo's Accelerated C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
1 #include <iostream>
2 #include <string>
3
4 int main()
5 {
6 std::cout << "enter name: ";
7 std::string name;
8 std::cin >> name;
9
10 const std::string greeting = "Hello "+name+"!";
11 const std::string spaces(greeting.size(), " ");
12 const std::string second = "* "+spaces+" *";
13 const std::string first(second.size(), "*");
14
15 std::cout << std::endl;
16 std::cout << first << std::endl;
17 std::cout << second << std::endl;
18 std::cout << "* " << greeting << " *" << std::endl;
19 std::cout << first << std::endl;
20 std::cout << second << std::endl;
21
22 return 0;
23 }
|
And I'm compiling using "g++ -o formatname formatname.cpp" only to get the following error:
formatname.cpp: In function ‘int main()’:
formatname.cpp:11: error: invalid conversion from ‘const char*’ to ‘char’
formatname.cpp:11: error: initializing argument 2 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(typename _Alloc::rebind<_CharT>::other::size_type, _CharT, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’
formatname.cpp:13: error: invalid conversion from ‘const char*’ to ‘char’
formatname.cpp:13: error: initializing argument 2 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(typename _Alloc::rebind<_CharT>::other::size_type, _CharT, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’ |
Any idea what's up? I copied the example line for line (aside from comments).
You set incorrect arguments for std::string constructor. In statement
const std::string spaces(greeting.size(), " ");
Instead of string literal " " a simple character shall be. That is the correct statement looks like
const std::string spaces(greeting.size(), ' ' );
Ahhh--thank you vlad. Didn't realize there was a different between double and single quote marks
Topic archived. No new replies allowed.