可能重复:
C++不推荐将字符串常量转换为'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 ===|
Run Code Online (Sandbox Code Playgroud)
警告引用这条线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;
}
Run Code Online (Sandbox Code Playgroud)
你以strncat()错误的顺序提供参数.第一个参数是要追加的字符串; 第二个参数是要追加的字符串.如上所述,您正在尝试将输入添加string到常量字符串"Hello",这是不正常的.您需要将其写为两个单独的字符串操作.
使用该std::string课程将为您节省很多悲伤.