-1
#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.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • 3
    VLAs are not part of the C++ standard and for this reason alone you shouldn't be using them. However even if VLAs are available, you're creating the array before `size` is initialized, so the program has undefined behaviour... – fabian Jan 04 '23 at 12:56
  • 2
    Whatever resource you're using to learn C++, it seems to teach you more C than C++. Please invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), learn about the standard C++ string class `std::string`. – Some programmer dude Jan 04 '23 at 12:57
  • 2
    Apart from anything else if you want to create an array based on a size input by the user, then you have to create the array **after** you get the size from the user, not before. – john Jan 04 '23 at 13:00
  • Find the introduction to arrays (and variables, and the order in which code is executed) in a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – molbdnilo Jan 04 '23 at 13:05
  • Why do you `#include ` and not use it? – nada Jan 04 '23 at 13:49
  • how there is 2 upvote? is there any language that use size before get it would make sense? – apple apple Jan 04 '23 at 14:11
  • *"example: size=10;"* -- don't say it; do it. Initialize `int size = 10;` and drop `cin>>size;`. Either this will make your problem easier to reproduce (no need to enter a size), or it will reveal a problem before the loop. – JaMiT Jan 04 '23 at 14:35
  • Also see [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/) – JaMiT Jan 04 '23 at 14:37

2 Answers2

0

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;
}
if4k
  • 19
  • 5
-2

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