Reputation: 2190
I need to read a non-constant C string into a C++ string. However, I only see methods in the string class that read constant C strings into the string class.
Is there anyway to do this in C++?
Update:
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string a;
// other code here
a(argv[0]);
cout << a << endl;
return 0;
}
error:
test.cpp: In function 'int main(int, char**)':
test.cpp:11:14: error: no match for call to '(std::string {aka std::basic_string<char>}) (char*&)'
a(argv[0]);
I did some more investigation, and replaced argv[0] with a constant string, and found that I still got a similar error message. A better question would now be: How can I declare an object and call its constructor later?
Upvotes: 0
Views: 101
Reputation: 124722
You're misinterpreting what the function signatures mean. The conversion takes its argument as a const char *
, but that doesn't mean that you cannot pass a char*
to it. It's just telling you that the function will not modify its input. Why don't you just try it out?
#include <iostream>
#include <string>
int main()
{
char str[] = "hello";
std::string cppstr = str;
std::cout << cppstr << endl;
return 0;
}
Upvotes: 4