C++:如何修改全局字符字符串?

C++: How do I modify a global char string?

在下面的代码片段中,我无法理解为什么 LineA 出现错误,而 Line B 却没有错误?

//Global 
char strA[80] = "A string to be used for demonstration purposes";

int t=60;  

int main(void)
    {    

        strA[80] = "I am trying to modify the source";  //Line A, gives error 

        t=60;   //Line B, no errors 

   }

错误是:

2 IntelliSense: a value of type "const char *" cannot be assigned to an entity of type "char" c:\users\hu\cplustutorial.cpp 69 12 CPLUStutorial

我没有 const 那样的 char 字符串,为什么会出现这个错误?

使用 MS VS 2010 编译。

char strA[80] = "A string to be used for demonstration purposes"; 初始化您的数组。

这个strA[80]表示该数组中的单个字符。如何将多个字符存储在一个字符中。使用 strcpy 复制新字符串。

您正在尝试将 strA 的第 80 个元素(顺便说一下,它不存在)分配给 const char*,而不是 char[] 本身。此外,您将问题标记为 C++,那么为什么使用 char[] 而不是 std::string

您必须了解一串字符(字符串文字)的类型为 const char *,并且您正试图将其存储在单个字符(char[80])中。这就是为什么它给你 error.Check 这个 http://www.whosebug.com/questions/20294015/.

在 C++ 中,字符串文字的类型是 const char[],而不是普通的 char[],所以您要尝试的是根据 C++ 标准,do 是非法的,因此您会看到错误。

为了修改字符串,您首先需要复制它,使用 C 库函数 strcpy 或(更好)使用 std::string.