2012-09-16 39 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; 
} 
相關問題