2012-09-16 38 views
-2

可能重复:
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; 
} 
+3

我认为更大的问题在于你使用'strncat()'完全不正确。 –

+3

你也应该使用std :: string而不是char数组。 – Borgleader

+3

您使用的是C字符串,而不是C++字符串。 C++的字符串类及其方法位于标题中,而不是(通常在C++中用编写)。 – sepp2k

回答

5

您正在以错误的顺序向strncat()提供参数。第一个参数是要附加到的字符串;第二个参数是要追加的字符串。正如你写的,你试图将输入string添加到常量字符串"Hello",这是不好的。你需要把它写成两个独立的字符串操作。

使用std::string类将为您节省很多的痛苦。

+0

感谢您的信息,我会研究std :: string类。赞赏。 –

1
char * strncat(char * destination, const char * source, size_t num); 

所以你的源和目的都是围绕着错误的方式。

+0

新手错误,非常感谢,现在可以使用。 –

4

由于您使用的是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; 
} 

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

3

一个更好的书写方式是使用字符串类并完全跳过字符。

#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; 
} 
相关问题