Cin input of multiple lines not iterating correctly

Viewed 44

I came from C so I'm trying to understand C++ input.

I want to read lines of input like so:

3
0 0 1 0
1 4 0 1
0 1 2 3

where 3 is the number of input lines I'm going to read next. My code is

  #include<iostream>
  #include<string>
   
  int main() {
    int n, k = 8;
    std::cin >> n;
    
   char lines[n][k];
   for(int i = 0; i < n; i++) 
     std::cin.getline(lines[i], k);
 } 

I should be able to read the n lines (because of the zeroth iteration) but it only goes for n-1, so it finishes the reading at n-2. I don't understand why and how to deal with it and properly read input like this.

Also: how would I do if I wanted to read the same way for a std::string? Would I use std::string *lines[n];?

1 Answers

you are trying to create variadic length arrays, they are not a part of standard C++.

You should be using a combination of std::vector and std::string:

#include <iostream>
#include <string> //std::string, std::getline
#include <vector>

int main() {
    int n;
    std::cin >> n;
    std::cin.ignore();

    std::vector<std::string> lines(n);

    for (auto& line : lines) {
        std::getline(std::cin, line);
    }
}

The std::ignore is needed because when using std::cin an additional \n is added after pressing enter. The next std::getline will be aborted when seeing the \n. So the ignore removes the next additional character from std::cin. read more on why does std::getline() skip input after a formatted extraction?

Related