繁体   English   中英

简单C ++代码引起的分段错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM