将非常量c字符串读入字符串类

时间:2014-09-26 06:02:26

标签: c++

我需要将非常量C字符串读入C ++字符串。但是,我只在字符串类中看到将常量C字符串读入字符串类的方法。

有没有在C ++中这样做?

更新

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    string a;

    // other code here

    a(argv[0]);

    cout << a << endl;
    return 0;
}

错误:

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]);

我做了一些调查,并用常量字符串替换了argv [0],发现我仍然收到类似的错误消息。现在一个更好的问题是:如何声明一个对象并稍后调用它的构造函数?

1 个答案:

答案 0 :(得分:4)

您错误地解释了功能签名的含义。转换将其参数视为const char *,但这并不意味着您无法将char*传递给它。它只是告诉你该函数不会修改它的输入。为什么不试试呢?

#include <iostream>
#include <string>

int main() 
{
    char str[] = "hello";
    std::string cppstr = str;
    std::cout << cppstr << endl;
    return 0;
}