0

Compiler version is 4.2 g++

#include <iostream>
#include <string>
using namespace std;
int main()
{

string a[10];
int i;
int N;
cin>>N;
for (i=0; i<N; i++)
{
    getline(cin,a[i]);
}
return 0;
}

When I input 2 . It asks for input once. When 3 then 2 times . And so on. Please solve. THANKS.

  • You will have undefined behavior if `N > 10`, you should change `a` to `vector a(N)`. – Casey Jun 14 '13 at 17:26
  • Feast your eyes on the many dupes: http://stackoverflow.com/search?q=%20getline%20skipping – chris Jun 14 '13 at 17:29

3 Answers3

2

The first getline call reads end-of-line character that is still sitting in the input buffer after the N is read.

Consider this as the following input:

3 First string
Second string
Third string

In your case, the first string is just empty.

If you want to ignore whitespaces after the N, write something like

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

(will skip to the end of line), or

cin >> N >> std::ws;

(will skip all whitespace characters, end of line included).

nullptr
  • 11,008
  • 1
  • 23
  • 18
0

After inputting a value for N, there is a \n (end of line) character left in the buffer. The first getline sees that as the first character, and returns an empty string. Simply do this:

string a[10];
int i;
int N;
cin>>N;
cin.ignore(INT_MAX);//flush buffer
for (i=0; i<N; i++)
{
    getline(cin,a[i]);
}

This will flush the buffer before the for() loop.

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • This suggests interactive input. Such solution will behave incorrect when stdin is redirected from file. – nullptr Jun 14 '13 at 17:29
0

the problem is that when press enter or space it is taking that also as input

 #include <iostream>
 include <string>
 using namespace std;
   main()
 {

string a[10];
int i;
 int N;
 cin >> N >> std::ws;
for (i=0; i<N; i++)
{

getline(cin,a[i]);

}
 return 0;
}
Rajesh M
  • 634
  • 11
  • 31