简体   繁体   中英

Segmentation Fault while accepting input

I am trying to accept the input from user where first line will be Integer to indicate number of testcases

if number is 3

Input will be like

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

I am using getline to read the input

My code

#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;
    }
}

Error:

3 

Segmentation fault(core dumped)

arr is an empty vector, so arr[i] = s; is going to access out of bounds. The [] operator does not grow the vector. It can only be used to access already existing elements.

You can't create an element of a vector using the [] indexing operator; your line arr[i] = s; is trying to assign a string to an element that doesn't (yet) exist .

There are several ways around this: first, you could use the push_back function to add a new element to the end of the vector, in each loop; second, you could use the resize member to pre-allocate a specified number of elements (which you can then use in the arr[i] = s; line); third - and perhaps simplest - you can 'pre-allocate' the elements of the vector by specifying the number of elements in the declaration (constructor), like this:

#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;
}

There are also a few other issues in your code that I have 'fixed' and commented on in the code I posted. Feel free to ask for further clarification and/or explanation.


EDIT: On the use of the cin.ignore(1); line I added, see Why does std::getline() skip input after a formatted extraction? (and the excellent answers given there) for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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