Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::cin won't work out of main() [duplicate]

Tags:

c++

cin

In the first block of code, the compiler gives no error. On the other hand, the second block of code gives the error error: 'cin' in namespace 'std' does not name a type.

First block of code:

#include <iostream>

int y;

int main(){
std::cout << "Enter something! \n";
std::cin >> y;
}

Second block of code:

 #include <iostream>

 int y;

 int main(){
 std::cout << "Enter something! \n";

 }

 std::cin >> y;

What causes such a behavior? And can I fix it?

If you need more details, feel free to ask in the comments.

like image 640
BoeNoe Avatar asked Dec 02 '25 09:12

BoeNoe


2 Answers

The way C++ works, you can't have executable code outside of a function. When the first block compiles, the compiler looks at the program something like this:

  1. Ok, time to start this program! Let's look in main()
  2. Ok, print "Enter something! \n"
  3. Now wait for user input and store it in y
  4. Ok, main() is done now, and there aren't any other functions... Guess the program's over!
  5. There's nothing outside main() to worry about, so I'm done.

The trouble with the second block is that the compiler only gets to step 2. Then it thinks something like:

  1. Well, main() is done
  2. Anything to pay attention to outside of main()?
  3. Oh, this looks like a new type declaration. But it's not.
  4. Throw an error!

If you're taking a class or teaching yourself C++, you'll come across structs and classes later in your study, and those will make this make a bit more sense. They're an example of the kind of syntax the compiler is trying to interpret this as.

like image 116
Harper Avatar answered Dec 04 '25 01:12

Harper


You fail at basic syntax of C \C++.

std::cin >> y; is a statement. Statement aren't allowed outside of function body, only declarations are. Compiler attempts to treat that line as declaration and first token in declaration is a type specifier. Hence you do get that error message.

like image 23
Swift - Friday Pie Avatar answered Dec 04 '25 01:12

Swift - Friday Pie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!