C++ if else语句代码报错求助:main函数返回值错误与clrscr未定义问题
Hi there! Let's walk through fixing your C++ code step by step—you've got a few small standard compliance and syntax issues here, but they're easy to resolve.
1. Fix the main function return type
C++ standards require that the main function returns an int type, not void. Your compiler is throwing an error because void main() isn't valid standard C++. To fix this:
- Change
void main()toint main() - Add
return 0;at the end of the function (this tells the OS the program ran successfully)
2. Remove non-standard <conio.h> and clrscr()/getch()
<conio.h> is a legacy DOS header that's not supported by most modern compilers (like GCC, Clang, or even recent MSVC versions). The functions clrscr() (clear screen) and getch() (wait for key press) are non-standard too:
- Delete
#include<conio.h>entirely - Remove the
clrscr();line (if you still want to clear the screen, you'd need a platform-specific method—for example,system("cls")on Windows orsystem("clear")on Linux/macOS, but note thatsystem()isn't ideal for production code) - Replace
getch();with standard input methods to pause the program (we'll cover this in the corrected code)
3. Fix the equality comparison bug
In your else if condition, you used vari=vari2—this is an assignment operator, not a comparison. It sets vari to the value of vari2 and then evaluates to that value (which will always be true unless vari2 is 0). To check if the two variables are equal, use the equality operator ==:
Change else if (vari=vari2) to else if (vari == vari2)
Corrected Full Code
#include<iostream> using namespace std; int main() { int vari, vari2; cout << "Enter a Variable: "; cin >> vari; cout << "Enter Another Variable: "; cin >> vari2; if (vari > vari2) { cout << "Variable 1 was greater"; } else if (vari == vari2) { cout << "Variables Are Equal"; } else { cout << "Variable 2 is Greater"; } cin.get(); cin.get(); // Two calls fix the leftover newline from previous cin inputs return 0; }
(Note: The second cin.get() is needed because after entering the second number with cin, there's a leftover newline character in the input buffer—without it, the first cin.get() would just read that newline and exit immediately.)
内容的提问来源于stack exchange,提问作者Kushagra Pandey

