![](/img/trans.png)
[英]What is the reason for a segmentation fault with this C++ code using lists?
[英]Need help locating the reason for “Segmentation fault” in this piece of C++ code
我有以下代碼
#include <cstdio>
#include <cmath>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
int main() {
int NoOfArr;
std::cin >> NoOfArr;
std::vector<std::vector<int>> VecOfVecs;
for(int i = 0; i <= NoOfArr; ++i) {
int x;
// Add all elements
std::vector<int> temp;
std::string str;
std::getline(std::cin, str);
std::istringstream sstr(str);
while(sstr >> x) {
temp.push_back(x);
}
std::cout << "reached2" << std::endl;
temp.erase(temp.begin());
VecOfVecs.push_back(temp);
}
return 0;
}
這應該接受一個輸入,例如
2
3 1 5 4
5 1 2 3 4 5
這個想法是我想制作一個向量向量(有點像 Python 中的嵌套列表),其中這個向量向量中的第一個元素是向量 {1,5,4},第二個元素是 {1,2, 3,4,5}。 我現在不關心輸入的第 2 行和第 3 行的第一個數字,所以我放棄了它們。 但是,讀取輸入似乎出了點問題,因為跳過了while
循環並且代碼返回了“分段錯誤”。 我對這門語言很陌生,所以我一直沒能找到導致這種情況的原因。 任何幫助表示贊賞。
我現在不關心輸入的第 2 行和第 3 行的第一個數字,所以我放棄了它們。
好吧,他們畢竟是有目的的。
實際上,如果您使用它們並將 stream 直接讀取到 arrays 中,而不是先讀取字符串,您可能會避免此錯誤。
現在發生的情況是,您首先從第 1 行消耗測試數據的數量,然后使用getline()
您仍然讀取第 1 行(讀取NoOfArr
時沒有消耗它的 EOL)。 該行為空,因此不會從中讀取任何數字,即您的while
循環被“跳過”,然后您嘗試擦除空數組的開頭...
在調用std::getline(std::cin,str)
之前使用std::cin.ignore()
) 。
在輸入NoOfArr
后按 Enter 鍵,getline 將其讀取為一行(因此它認為 for 循環中的第一行輸入為空行)。 它在第一次迭代中沒有將任何內容推入向量,但隨后它嘗試擦除temp.begin()
。 這給你分段錯誤。
使用std::cin.ignore()
將跳過std::getline(std::cin,str)
讀取您在輸入第一個輸入后按下的回車鍵。 這可能會解決您的錯誤。 我希望這有幫助。
您需要添加std::cin.ignore ();
在std::cin >> NoOfArr;
.
std::cin >> NoOfArr;
不會從輸入 stream 中刪除行尾字符,這意味着對getline
的下一次調用返回一個空字符串。 結果,向量temp
為空,因此temp.begin()
將無效的迭代器傳遞給temp.erase()
。
無論如何,代碼都應該測試temp
是否為空,因為它可能是空的,這取決於提供給程序的輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.