【问题标题】:warning: deprecated conversion from string constant to 'char*' [duplicate]警告:不推荐将字符串常量转换为 'char*' [重复]
【发布时间】:2012-09-09 05:09:34
【问题描述】:

可能重复:
C++ deprecated conversion from string constant to ‘char*’

我正在研究 C++ 中的字符串,并尝试了一个练习来试验字符串库中定义的一些函数的行为。我昨天编译了相同的程序,一切正常,没有任何警告或错误。但是,今天我再次尝试编译程序,但收到以下警告。

D:\C++ CodeBlocks Ex\Strings\main.cpp||In function 'int main()':|
D:\C++ CodeBlocks Ex\Strings\main.cpp|11|warning: deprecated conversion from string constant to 'char*'|
||=== Build finished: 0 errors, 1 warnings ===|

警告指的是这一行strncat("Hello",string,STRMAX-strlen(string));。我不确定,但我怀疑 strncat 函数不喜欢必须将文字数组与字符串常量连接起来的想法。对此的任何帮助将不胜感激。

#include <iostream>
#include <string.h>

using namespace std;

int main(){
    #define STRMAX 599
    char string[STRMAX+1];
    cout<<"Enter name: ";
    cin.getline(string,STRMAX);
    strncat("Hello",string,STRMAX-strlen(string));
    cout<<string;
    return 0;
}

【问题讨论】:

  • 我认为这里更大的问题是您完全错误地使用了strncat()。
  • 另外你应该使用 std::string 而不是 char 数组。
  • 您使用的是 C 字符串,而不是 C++ 字符串。 C++ 的字符串类及其方法位于 标头中,而不是 (在 C++ 中通常写为 )。

标签: c++


【解决方案1】:
char * strncat(char * destination, const char * source, size_t num);

所以你的来源和目的地是错误的。

【讨论】:

  • 新手错误,非常感谢,现在可以使用了。
【解决方案2】:

您以错误的顺序向strncat() 提供参数。第一个参数是要附加到的字符串;第二个参数是要附加的字符串。如前所述,您尝试将输入string 添加到常量字符串"Hello",这是不行的。您需要将其编写为两个单独的字符串操作。

使用std::string 类将为您省去很多麻烦。

【讨论】:

  • 感谢您的信息,我将研究 std::string 类。赞赏。
【解决方案3】:

由于您使用的是 C++,我建议您避免使用 char* 并改用 std::string。 如果需要传入char*,字符串类有一个c_str()方法,以const char*的形式返回字符串。

使用字符串类时的连接就像"Hello " + "World!" 一样简单。

#include <iostream>
#include <string>

const int MaxLength = 599;

int main() {
    std::string name;

    std::cout << "Enter a name: ";
    std::cin >> name;

    if (name.length() > MaxLength) {
        name = name.substr(0, MaxLength);
    }

    // These will do the same thing.
    // std::cout << "Hello " + name << endl;
    std::cout << "Hello " << name << endl;

    return 0;
}

这并不能完全回答您的问题,但我想它可能会有所帮助。

【讨论】:

    【解决方案4】:

    更好的编写方法是使用字符串类并完全跳过字符。

    #include <iostream>
    #include <string>
    
    int main(){
        std::string name;
        std::cout<<"Enter name: ";
        std::getline(std::cin, name);
        std::string welcomeMessage = "Hello " + name;
        std::cout<< welcomeMessage;
        // or just use:
        //std::cout << "Hello " << name;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-20
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2010-12-04
      相关资源
      最近更新 更多