Why can't i use loops to take input of a char array?

119 Views Asked by At
#include<iostream>
#include<string>
using namespace std;
int main()
{
    int size; char str[size]; cin>>size;
    for(int i=0; i<size; i++)
    {
        cin>>str[i];
    }
    return 0;
}

example: size=10; I was expecting this program to take 10 inputs but it is taking severral inputs. if it has something to do with cin then please explain.

2

There are 2 best solutions below

8
On

I fixed it. Try it.

#include<iostream>
#include<string>
using namespace std;
int main()
{
    int size; 
  cin>>size;
  char str[size]; 
    for(int i=0; i<size; i++)
    {
        cin>>str[i];
    }
    return 0;
}
2
On

It hasn't anything to do with the cin, to put 10 inputs you need to change the line 7 to "for (int i=0; i<<size; i++)" I haven't tried it yet but maybe it would solve your problem