[英]Segmentation fault caused by simple c++ code
這里絕對是初學者。 我正在嘗試解決此問題,但出現了細分錯誤。 我嘗試尋找解決方案,但找不到為什么該方法不起作用。
要重現該錯誤,只需復制以下代碼,然后將其粘貼到上方鏈接下的編輯器中即可。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
//using namespace std;
int main() {
int n, q;
std::cin >> n >> q;
std::vector<std::vector<int>> arr;
// handle n lines representing the arrays
for (int i = 0; i < n; i++) {
std::vector<int> numbers;
std::string line;
getline(std::cin, line);
std::istringstream iss(line);
int enterNumber;
while (iss >> enterNumber)
{
numbers.push_back(enterNumber);
}
arr.push_back(numbers);
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
std::cin >> x >> y;
std::cout << arr[x][y];
}
return 0;
}
我想念什么? 為什么不起作用?
導致分段錯誤的輸入:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
預期產量:
5
9
1) getline(std::cin, line);
。 行包含空格和數字。
2)處理行中的空格
3)處理數組長度的第一個int。 (您嘗試在數組本身中添加數組長度)
這是工作代碼供參考。 (通過所有測試用例)
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector< vector<int> > arr;
int temp, array_count;
for(int i = 0; i < n; i++) {
vector<int> numbers;
cin>>array_count;
for(int j = 0; j < array_count; j++) {
cin>>temp;
numbers.push_back(temp);
}
arr.push_back(numbers);
numbers.clear();
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
cin >> x >> y;
cout << arr[x][y]<<"\n";
}
return 0;
}
要解決分段錯誤,只需添加std::cin.get();
在第一個std::cin
(主函數中的第三行)。
發生分段錯誤是因為getline(std::cin, line);
在for循環的第一次迭代中返回空字符串。 看到這個 。
請注意,即使解決了分段錯誤問題,您的代碼仍然是錯誤的(無法解決挑戰):p
嘗試這個:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
//using namespace std;
int main() {
int n, q;
std::cin >> n >> q;
std::cin.get();
std::vector<std::vector<int>> arr;
// handle n lines representing the arrays
for (int i = 0; i < n; i++) {
std::vector<int> numbers;
std::string line;
getline(std::cin, line);
std::istringstream iss(line);
int enterNumber;
while (iss >> enterNumber)
{
numbers.push_back(enterNumber);
}
numbers.erase(numbers.begin()); // because first value is k
arr.push_back(numbers);
}
// handle q lines representing i, j
int x, y;
for (int i = 0; i < q; i++) {
std::cin >> x >> y;
std::cout << arr[x][y] << std::endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.