0

I was doing some coding and I noticed something, Usually for an array of integers if we do like this:

int x;
cin>>x;
int a[x];
for(int i=0;i<x;i++) cin>>a[i];
for(int i=0;i<x;i++) cout<<i<<" "<<a[i]<<endl;

for this input

3
11
12
13

we get the output like this

0 11
1 12
2 13

while on the other hand, If I do something with an array of strings:

 cin>>query_count;
    string queries[query_count+1];
    for(int i=0;i<=query_count;i++) getline(cin,queries[i]);
    for(int i=0;i<=query_count;i++) cout<<i<<" "<<queries[i]<<endl;

For this input

3
a
b

I am getting the output like this

0
1 a
2 b

Can someone explain what is happening!

Caleth
  • 35,377
  • 2
  • 31
  • 53
  • Don't post links to images of (what I suppose is) text. If you have text input and output to show, then copy-paste it into the question as text. – Some programmer dude Mar 02 '21 at 12:13
  • 3
    By the way, C++ doesn't have [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) which makes your code invalid and not proper C++. If you want an "array" whose size is set at run-time use `std::vector` instead. – Some programmer dude Mar 02 '21 at 12:14
  • 1
    Think about the `Enter` key you pressed to give the input for `query_count`. That `Enter` key is added as a newline in the input buffer. Which the first `getline` call will read. I'm sure someone will find a suitable duplicate of this problem. – Some programmer dude Mar 02 '21 at 12:27
  • Also your code for strings doesn't match the input and and output you show. When you input `3` as the amount of input the code will require **`4`** strings. – Some programmer dude Mar 02 '21 at 12:29
  • tldr: `cin.ignore();` between reading the count and reading the first query – Caleth Mar 02 '21 at 12:35

0 Answers0