字符常量数组为空,即使已为其赋值 [C++]

Character Constant Array is empty, even though values has been assigned to it [C++]

本文关键字:赋值 C++ 数组 字符常量      更新时间:2023-10-16

我在字符常量数组中分配字符串值时遇到问题。每次将字符串值分配给字符数组的特定位置时。在字符串变量中获取新值后,数组中的位置值将初始化为空字符串。我努力把它拿出来,但徒劳无功。以下是我正在使用的代码:

        const char *array[40];
        string line="";
        ifstream myfile( "text.txt");
        if (myfile) 
          {
            int in=0;
          while (getline( myfile, line ))  
            {
              array[in]=line.data();
                  in++;
           }
          myfile.close();
          }
        else return;

现在,数组变量具有所有空字符串值。请让我知道我该怎么做?

您正在访问string对象line的内部数据缓冲区,并让array[in]指向它。读取下一行时,此缓冲区要么被覆盖,要么可能指向不同的内存位置,以便先前写入的array[in]指向已被新内容覆盖或根本无效的内存。

如果要使用 const char*[...] 数组,请先复制缓冲区:

array[in]= strdup(line.c_str());

进一步请注意,line.data()为您提供了一个数组,但不保证最后有一个终止0x0。请参阅 cppreference.com string::data()文档