-2
#include <iostream>
#include <string.h>
using namespace std;

/* Variables */
int N = 0;
int M = 0;
int Px, Py;
int gcount = 0;
cin >> N >> M;
string maze[100];

/* Define Functions */
void read_maze(int);
void scan_maze(int);
void print_maze();

This is a code snippet for a text-based game I am making and when I run it, I get the following error:

main.cpp:10:1: error: 'cin' does not name a type
   10 | cin >> N >> M;
      | ^~~

I am not able to debug the problem with the code. Any ideas?

Editor: Atom

Operating System: Windows 10

Compiler: MinGW

Thanks

VMSM
  • 15
  • 4
  • 4
    You may not use this statement cin >> N >> M; outside a function as for example outside main. – Vlad from Moscow May 29 '21 at 11:16
  • How odd, that global commands have now been demoted. – CodeLurker May 29 '21 at 11:20
  • 2
    I'd recommend you'd start with a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), instead of trying to learn a complex language like c++ by trial and error. This is not the place to tutor you through, though. – πάντα ῥεῖ May 29 '21 at 11:22
  • `cin` is an object (its type is `std::istream`). Reading from `cin` is only possible within a function block. You are attempting to read outside a function block. Outside a function block, the only things permitted are declarations (of types, variables, and functions). `cin >> N >> M` is a statement, and such statements are only valid inside a function block. – Peter May 29 '21 at 13:44

1 Answers1

1

You must use a statement inside of a function, e.g.

#include <iostream>

int main() {
    /* Variables are fine at global scope, but you should prefer local ones */
    int N = 0;
    int M = 0;
    int Px, Py;
    int gcount = 0;
    
    /* Here's the problematic statement from before */
    std::cin >> N >> M;
    ...
}
Zeta
  • 103,620
  • 13
  • 194
  • 236