Mahmoud Anwer February 2016

Storing lines of input into a vector

In my program I am trying to take from the user lines of input actually names then storing them into a vector.

I wrote my own code but I got a runtime error telling me that "string subscript out of range".

This is my code

const int LEN = 100;
struct Case{
public:
int No_People;
vector<string> Names;
vector<string> Results;
void Set_Data(){
    cin >> No_People;
    int Size = No_People;
    char Line[LEN];
    for (int i = 0; i < Size; i++){
        cin.getline(Line, LEN);
        Names.push_back(Line);
    }
  }
}

Answers


iksemyonov February 2016

There's no need to use a char[] array, use std::string instead, especially given that you already are using it.

Note to OP: cin.getline() is this one:

std::istream::getline(char*, int)

The one you ned to use for std::string's is this one:

std::getline(istream&, string&)

struct Case{
public:
    int Size;
    vector<string> Names;
    vector<string> Results;
    void Set_Data(){
        std::string temp;
        cin >> Size; cin.ignore();
        for (int i = 0; i < Size; i++){
            std::getline(cin, temp);
            Names.push_back(temp);
        }
    }
}

As far as compile errors go, always:

  • quote the exact error messgae
  • tell the line it happened at
  • show the code that contains the line and the relevant classes/methods


kiran February 2016

Most probably you are accessing the string using subscript which is out of index. It will be easy to answer if you point at which line you are getting the error.


Loki Astari February 2016

Personally I would define a class to represent a line. Then you can use stream iterators to load the vector.

class Line
{
    std::string   line;
    public:
        // Operator to convert a line back to a std::string
        operator std::string const&() const {return line;}

        // Friend function to read a line from a stream.
        friend std::istream& operator>>(std::istream& in, Line& data)
        {
            return std::getline(in, data.line);
        }
 };

 int main()
 {
     int countOfPeople;
     std::cin >> countOfPeople;

     std::vector<std::string>  lines;
     std::copy_n((std::istream_iterator<Line>(std::cin)), countOfPeople,
                 std::back_insert_iterator(lines));
 }

Post Status

Asked in February 2016
Viewed 3,553 times
Voted 8
Answered 3 times

Search




Leave an answer