1

I have to input an int n, and read n lines in a string array. But when I test my code, for example, I put 3, it will read only 2. I found that I should use vectors, but why, is there any way easier than vectors to read n lines ?

Example code:

#include <iostream>
using namespace std;

int main() {

    int n;
    cin >> n;
    string niz[n];

    for (int t1 = 0; t1 < n; t1++) {
        getline(cin, niz[t1]); }

    for (int t2 = 0; t2 < n; t2++) {
        cout << niz[t2] << endl; }
}
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
NikolaTEST
  • 100
  • 11
  • 1
    As mentioned [recently](http://stackoverflow.com/questions/30833225/are-arrays-not-dynamically-allocated-in-c) in this queue, VLA's arent a standard feature. Also elaborate about _"and the third will be false."_ please. Your code should work just fine. – πάντα ῥεῖ Jun 14 '15 at 19:30
  • It doesn't work. I would put this here if it works fine. – NikolaTEST Jun 14 '15 at 19:34
  • _"It doesn't work"_ Isn't helpfuly for anyone. So some mentions about given [inputs, expected outputs](http://ideone.com/2UTSNf)? Improve your question please. – πάντα ῥεῖ Jun 14 '15 at 19:36
  • I don't know how ideone knew this, because I didn't paste the code. Wow. However, here, check: http://ideone.com/2UTSNf – NikolaTEST Jun 14 '15 at 19:38
  • I made it knowing about your code of course. – πάντα ῥεῖ Jun 14 '15 at 19:41
  • *"I found that I should use vectors"* Yes, you really should. *"is there any way easier than vectors to read n lines"* No, `std::vector` is the right tool for this job. – Baum mit Augen Jun 14 '15 at 19:51

2 Answers2

3

The problem is that when you read the number of lines the newline is still left in the stream, so the first line that is read is just an empty line (what remains after the number that you input).

See and example exchange of input and output when I modify the program a little to prefix each line of output:

C:\so-test>test
3
Mary had
A little lamb.
line [0]:
line [1]: Mary had
line [2]: A little lamb.

For the moment, I'll leave the solution as an exercise for the reader.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
0

In the first for loop, first iteration takes what's left in that row after you input n. You can just put cin.ignore(); before the first for loop to ignore the rest of that line. It should work now.

Bartic
  • 78
  • 1
  • 10