簡體   English   中英

當用鍵盤輸入覆蓋元素中已存儲的值時,為什么字符串類型數組不接收數據?

[英]Why does a string type array doesn't take data when you overwrite the already stored values in the elements with input from keyboard?

我正在嘗試將“ 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM