字符常量数组为空,即使已为其赋值 [C++]
Character Constant Array is empty, even though values has been assigned to it [C++]
我在字符常量数组中分配字符串值时遇到问题。每次将字符串值分配给字符数组的特定位置时。在字符串变量中获取新值后,数组中的位置值将初始化为空字符串。我努力把它拿出来,但徒劳无功。以下是我正在使用的代码:
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()
文档
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 用C++中的sscanf赋值
- 为std::string的某个索引赋值
- 重载Singly Linked List中的赋值运算符
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- gtest_使用setargpointee在函数中赋值
- 非常量变量只读位置的赋值
- 使用赋值运算符重载从类中返回jobject
- C++数据文件、数组和计算赋值
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 全局作用域中函数指针的赋值
- 错误:在为指针赋值时,void值没有被忽略
- 标准库类型的赋值运算符的引用限定符
- 关于 c++ 函数中指针赋值的简单问题
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- cin >> int 给定一个字符串将 int 赋值为 0
- if 子句中的赋值不起作用
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?