c++ - 为什么当你用键盘输入覆盖元素中已经存储的值时,字符串类型的数组不取数据?

标签 c++ visual-studio ubuntu-18.04

我试图将“01”和“10”之类的值存储到一个数组中,但 int 数组会将“01”作为“1”。因此我决定使用字符串数组。在声明字符串数组时,我用

对其进行了初始化
string array[n] = {0};

编译代码时显示错误:

"terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_constructnull not valid"

虽然只是将数组的类型更改为整数,但它工作正常。

我试着不初始化

string array[n]={0};

然后代码就可以正常工作了!

我们是否可以得出结论,字符串类型数组不能覆盖元素中已经存储的值?

#include<bits/stdc++.h>

using namespace std;
int main(){
    int n;
    cin>>n;
    string arr[n] = {0};
    for(int i=0; i<n; i++){
    cin>>arr[i];
    cout<<arr[i];

    }  
 }

这是代码的输出:

1
terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_M_constructnull not valid

最佳答案

你有两个问题

string arr[n] = {0};

首先,n 不是编译时常量,因此 arr 是 VLA(可变长度数组)。这些不是标准的,仅作为某些编译器的扩展支持。您可以使用 -pedantic 编译器标志来停止编译。

其次,= {0} 部分将使用整数 0 初始化数组中的第一个字符串。由于 0 也是空指针值,因此它被视为指针,编译器会尝试从空指针构造字符串。这是未定义的行为,在这种情况下 std::string 会抛出异常。

要解决所有这些问题,请使用 std::vector(可以具有运行时大小)并让它默认为您构建所有元素。你可以这样做

std::vector<std::string> arr(n);

关于c++ - 为什么当你用键盘输入覆盖元素中已经存储的值时,字符串类型的数组不取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54711109/

相关文章:

c++ - 通过指针或值修改动态二维数组行

c++ - mbed OS 5 项目中链接了哪些文件?

c++ - 在 C++ 中从管道获取 Gnuplot 版本

c++ - 任何用于将 borland c++ 转换为 visual studio C++ 的代码转换工具

c# - MSBuild:构建 DefineConstants 值

c++ - 如果不使用它,访问数组外的数据是否不正确?

c# - Visual Studio 在设计器模式下打开我的类文件 (.cs)

python - pymongo.errors.OperationFailure : command insert requires authentication

python - Ubuntu 18.04 上 Python 的 os.system 和 subprocess.check_output 中莫名其妙的 shell 命令取消转义行为

java - 在 R 3.6 上为 ubuntu 仿生海狸安装 rJava 时出现 "Unable to run a simple JNI program"错误消息