簡體   English   中英

接受輸入時出現分段錯誤

[英]Segmentation Fault while accepting input

我正在嘗試接受來自用戶的輸入,其中第一行將是 Integer 以指示測試用例的數量

如果數字是 3

輸入會像

3
Hello world
hey there, I am John
have a nice day

我正在使用getline讀取輸入

我的代碼

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    int n;
    cin >> n;

    vector<string> arr;

    for(int i=0; i<n; i++){
        string s;
        getline(cin, s);
        arr[i] = s;
    }
}

錯誤:

3 

Segmentation fault(core dumped)

arr是一個空向量,所以arr[i] = s; 將訪問越界。 []運算符不會增大向量。 它只能用於訪問已經存在的元素。

不能使用[]索引運算符創建向量的元素; 你的行arr[i] = s; 正試圖將一個字符串分配給一個不(還)存在的元素。

有幾種方法可以解決這個問題:首先,您可以使用push_back函數在每個循環中向向量的末尾添加一個新元素; 其次,您可以使用resize成員預先分配指定數量的元素(然后您可以在arr[i] = s;行中使用); 第三個——也許是最簡單的——你可以通過在聲明(構造函數)中指定元素的數量來“預分配”向量的元素,如下所示:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string> // Need this for the "getline()" function definition

using namespace std;

int main()
{
    size_t n; // Indexes and operations on std::vector use "size_t" rather than "int"
    cin >> n;
    cin.ignore(1); // Without this, there will be a leftover newline in the "cin" stream
//  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // More precise, actually!
    vector<string> arr(n);
//  arr.resize(n); // Alternative to using 'n' in constructor
    for (size_t i = 0; i < n; i++) {
        string s;
        getline(cin, s);
        arr[i] = s;
    }

    for (auto s : arr) cout << s << endl; // Just to confirm the input values
    return 0;
}

您的代碼中還有一些其他問題,我已經“修復”並在我發布的代碼中進行了評論。 隨時要求進一步澄清和/或解釋。


編輯:關於cin.ignore(1); 我添加的行,請參閱為什么 std::getline() 在格式化提取后跳過輸入? (以及那里給出的優秀答案)了解更多詳情。

暫無
暫無

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

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