How do I fix this compiler error - c++

Been working on this for the past 5 hrs or so. I have done the research and tried to see what was wrong but I couldn't grasp what was missing. If anyone can help me solve this minor issue I would be grateful
Here's the code
#include <iostream>
using namespace std;
bool isPrime (int num);
int main()
{
int num=0;
cout << "Enter a number and I'll tell you whether it is prime: ";
cin >> num;
if (isPrime(num)==true)
cout << num << " is prime.";
else
cout << num << " is NOT prime.";
return 0;
}
bool isPrime(int input)
{
if(input<1)
return false;
else if (input == 1||input ==2 ||input==3)
{
return true;
}
else
{
for(int i=2; i<input; i++)
{
if(input%i==0)
return false;
}
return true;
}
}
It gives me this compiler error
./main.cpp: In function ‘int main()’:
./main.cpp:31:6: error: redefinition of ‘int main()’
int main()
^
./main.cpp:10:5: error: ‘int main()’ previously defined here
int main() {
^
I'm not sure what it means, but from where I researched, it means there are two mains but I have only one.

The following code compiles well with TurboC++ on windows and gives the appropriate result according to as required:
#include <iostream.h>
enum bool {true, false};
bool isPrime (int num);
int main()
{
int num=0;
cout << "Enter a number and I'll tell you whether it is prime: ";
cin >> num;
if (isPrime(num)==true)
cout << num << " is prime.";
else
cout << num << " is NOT prime.";
return 0;
}
bool isPrime(int input)
{
if(input<1) {
cout<<"Negatives not allowed"<<endl;
return false;
}
else if(input == 1) {
return false;
}
else if (input ==2 ||input==3) {
return true;
}
else {
for(int i=2; i<input; i++) {
if(input%i==0)
return false;
}
return true;
}
}

Make sure you're not including any additional files that also define main()
If you're working in visual studio, you should check the solution explorer for other .cpp files, especially if you've moved this over from an old solution, where you could've forgotten to get rid of old references. If that fails, you could just copy and paste the code that you do have into a new project, since what you have shouldn't be producing the error that you're getting.

Are you including this file from multiple others without an include guard? Or you could possibly have another main written in another cpp file in your project that you forgot about, in which case make sure you do not build that one with the project by excluding, or creating an entirely new project and adding each file you need individually.
I have found that with most IDE's, and even with command-line compiling, when you get really weird errors and cannot fix them creating a new project can solve many of them.

Your exact code runs perfectly on my compiler. So there is no problem on your code. This kind of problem always happens for you compiler. I think you are using an IDE in which you have created a project and added another code, that has a main() function too. So you can easily resolve this by creating a new project from scratch and copy paste this code.

Related

Creating a simple crackme program in C++ problems with variable and input

So I am trying to learn C++ so I can learn some reverse engineering that why I am trying to create this simple crack me program to get a foundation going and not take someone else's project as I choose my own path. However I am using CodeBlocks as the other IDEs were not being cooperative and am enjoying it and has given me some error and two lines. Below is the following code. So there errors are the following:
||=== Build: Debug in SimpleProgram (compiler: GNU GCC Compiler) ===|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In member function 'int checker::processing(int)':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|15|warning: no return statement in function returning non-void [-Wreturn-type]|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In function 'int main()':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|22|error: 'x' was not declared in this scope|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
#include <iostream>
using namespace std;
class checker{
public:
int number;
processing(int x){
x = number;
if ( number == 10 ){
cout << "Well done!";
} else {
cout << "Keep trying!";
}
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number";
cin >> cracking.processing(x);
return 0;
}
Image of the project and error
A function always has a return type, even if your not attempting to return anything it will have the void signature. If your intent was to take input of a number passed from main and display it via a function in your class checker through an object of the same, this is how it would look like:
#include <iostream>
using namespace std;
class checker{
public:
int number;
void processing(int x)
{
if (x==10)
cout << "Well done!";
else
cout << "Keep trying!";
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number \n";
int n;
cin >> n;
cracking.processing(n);
return 0;
}
I've cleaned the code up and included comments that serve as notes:
#include <iostream>
using namespace std;
class checker{
public:
void setnumber(int i){ //it's a good habit to put variables in private and access them with a public function
this->number = i;
};
int processing(int x){ //x is just a placeholder value for whatever you put in here. You can't use it in the rest of the program
if ( x == 10 ){
cout << "Well done!" << endl;
return 1; //this condition indicates success
} else {
cout << "Keep trying!" << endl; //the endline just makes it so you aren't typing on the same line as the message
return 0; //this condition indicates success hasn't been reached yet
}
}
private:
int number;
};
int main()
{
checker cracking;
cracking.setnumber(10); //the number is set to 10
int i, l; //i is the guess number, l is a condition for the loop
cout << "Please enter in the correct number" << endl;
do{ //this loop sets it up so that you can have multiple tries
cin >> i;
l = cracking.processing(i);
}while(l!=1); //and this condition (the return value of processing(), breaks the loop on success
return 0;
}
The main issue that popped out at me was the use of x.
Trying to set x to number. In functions, the parameters are just placeholder values for arguments that will be passed into later. Then later on when you tried to use x as an input in the main() program. You were calling that function (using it) and needed an int as input.
Don't worry. It's confusing in the beginning for everyone (although to be fair, as you progress you'll just find new things to be confused about. It never really stops). Keep at it and it'll all make sense in time.

Changing variables during if-else if- else statements in C++

As I'm sure the question makes clear, I'm new and learning and I'm sure many will wonder why ask.....cause I get the rest of it, just not this. I am using C++ and am trying to make a self guessing program, that uses an algorithim given to me. I have played with this section of code multiple ways and so far the one thing I have narrowed down, is what its not doing, and I want to both understand why and how to fix it because nothing I have tried is working. The basic version of the code I have been playing with is this:
// test_room.cpp : This file contains the 'main' function. Program execution
//begins and ends there. This is where
//I am going to test some code to understand my mistakes and how to fix
//them.
//
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
int main()
{
char play = 'y';
while (play == 'y')
{
int bad = 27;
int a = 50;
int b = 1;
int good = ((a - b) / 2);
int s = 0;
cout << "\nBegin?";
cin >> play;
do
{
++s;
if (good > bad)
{
cout <<"\n" <<good;
cout <<"\n" << s;
--a;
}
else if (good < bad)
{
cout << "\n"<<good;
cout <<"\n" << s;
++b;
}
else
{
cout << "good job";
}
} while (s < 50);
}
cout << "\nOK\n";
return 0;
}
What my question is I have tried moving the variables, I have fixed brace issues, I have tried using cin>>good>>a or b(depending on >< ) and so far I can not manipulate variables a or b to get it to try to guess or figure out the number 27, all it does is repeat 24 50 times. What do I need to do to change the values of a and b based on the algorithim?
Good and bad are never changed in the loop, I don't really understand the purpose of you algorithm(it looks like a binary search, but not really), but if you aren't changing any values that the if conditions evaluate in the loop, then none of the other conditions will ever be evaluated.

Finding prime numbers and then putting the prime numbers into an output file

So I have an assignment for class in which I have to ask the user for an integer in between 1 and 3000. Then my program should be able to tell if the integer is a prime number or not. Lastly, I would have to put that integer into a file, but only if it is a prime number. But my issue is my syntax, I am not sure if it's right(well actually obviously it's not because I keep getting errors). Is it possible to open a file in a function? and if so does it become a parameter?
I have been going through my textbook and googling as much as possible for some guidance but I'm still feeling lost. Any advice would help.
Edit: My logic as far as the numbers work, however when I add the code to write to a file, I'm now getting errors.
The two errors are
C2440 initializing: cannot convert from constant char to int (line 18)
C2079 myfile: uses undefined class'std::basic_fstream <>char,std::char_traits>'
Here's my code so far!
// Project 5.cpp : Defines the entry point for the console application.
//
#include <fstream>
#include "stdafx.h"
#include <iostream>
using namespace std;
//functions
void prime(int x);
//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");
int main()
{
do
{
cout << "Enter an integer between 1 and 3000 \n";
cin >> x;
if (x == 1)
{
cout << x << " is not a prime number.\n";
}
else if (x < 1 || x>3000)
{
cout << x << " is an invalid number. \n";
}
else
{
prime(x);
}
cout << "Do you want to enter another number? Y/N \n";
cin >> answer;
} while (answer == 'y' || answer == 'Y');
myfile.close();
return 0;
}
void prime(int x)
{
if (x == 2)
{
cout << "Yes, " << x << " is Prime\n";
}
else
{
for (i = 2; i < x; i++)
{
if (x%i == 0)
{
cout << x << " is not a prime number\n";
break;
}
}
if (x == i)
{
cout << "Yes, " << x << " is Prime\n";
myfile << x ;
}
}
}
#include "stdafx.h" includes a pre-compiled header file when using Microsoft Visual Studio. Check to see if that file exists and if it is correct (depending on the errors you see).
There is no reason to pass the outputFile into the prime() function since you are opening and closing it in the function. Although it works just fine if you do.
It is a parameter of the function call (if that is your question) and is a global variable since it is defined outside the main() function.
As some one else suggested the code functions if the aforementioned #include "stdafx.h" is removed, but I am not sure how that affects the compilation in Visual Studio.

Program does nothing when run

This program is a very simple one, a guessing game, however the issue is that when I compile it, it displays no errors. When I run it, it does nothing. I have tried fixing it, in that I moved the code within the guess() function back into main, and that works, printing "Enter a number between 0 & 100: ". Then when you do enter a number, it freezes, and this is probably caused by the lack of stop condition for the recursion. As I am not returning integers, as main has to, I reverted back to using the guess() function, and I have no idea why it doesn't work.
#include <iostream>
#include <cstdlib>
#include <string>
int computer = rand() % 101;
int user = 0;
int counter = 0;
std::string guess();
int main(void) {
std::string guess();
return 0;
}
std::string guess() {
std::cout << "Enter a number between 0 & 100: ";
std::cin >> user;
if(!(std::cin >> user)) {
return "You entered a non-numeric. Try again. Tries will not be added.";
std::cin.clear();
std::cin.ignore(10000, '\n');
std::string guess();
}
else {
if(user == computer) {
std::cout << "You guessed the right number of " << computer << " in " << counter << " tries.\n";
}
else {
if(user < computer) {
return "The answer is higher. Try again.";
}
else if(user > computer) {
return "The answer is lower. Try again.\n";
}
counter++;
std::string guess();
}
}
}
Note that I am very much a novice programmer, and the issue is probably quite simple and obvious, but I just can't see it. Thanks.
The problem is, that your often write std::string guess(); in order to call your guess() method (e.g. in main. But that doesn't call the method. What it actually does is to declare a new function guess, which is never called (see also Most vexing parse). To only call the method simply write guess();, or auto result = guess(); if you actually want to use the return value.
Also there is an error in this part of your code (see comment):
if(!(std::cin >> user)) {
return "You entered a non-numeric. Try again. Tries will not be added.";
// the following lines are never executed, since you already returned.
std::cin.clear();
std::cin.ignore(10000, '\n');
std::string guess();
}
Issue
The issue is indeed simple and obvious:
std::string guess();
It's obvious that you would like to call your "guess" function, but instead you've just declared it inside "main" and inside "guess".
These declarations are similar to the declaration that you made on the next line after int counter = 0;. It tells compiler that if it encounters call to the function named "guess" it should know that it is a function that takes no arguments and returns std::string.
So, the issue is that instead of calling a function, you declared it several times;
Solution
When you want to call your function you should do it like this:
std::string result = guess();
But since you return some message from guess() I think you should add output after that:
std::cout << result << std::endl;
Actually, I think it would be better to remove return value altogether. In order to do that you should modify "guess" function in a following way:
change return type from std::string to void
replace return with std::cout <<.
Many mistakes.
Firstly you don't need string return type.
So change std::string guess() to void guess()
Then use cin.fail() instead of !(cin>>user)
Also use else if rather than
else{
if{
To generate random number, firstly intialize seed and that can't be done globally, so generate random number in main and pass it in guess function.
To summarize here is the code
#include <iostream>
#include <cstdlib>
#include <string>
#include<ctime>
int user = 0;
int counter = 0;
void guess(int computer);
int main(void) {
srand(time(NULL));
int computer = rand() % 101;
guess(computer);
return 0;
}
void guess(int computer) {
std::cout << "Enter a number between 0 & 100: ";
std::cin >> user;
//std::cout<<computer<<std::endl;
if(std::cin.fail()) {
std::cout<< "You entered a non-numeric. Try again. Tries will not be added.";
std::cin.clear();
std::cin.ignore(10000, '\n');
guess(computer);
}
else if(user == computer) {
std::cout << "You guessed the right number of " << computer << " in " << counter << " tries.\n";
return;
}
if(user < computer) {
std::cout<< "The answer is higher. Try again.\n";
}
else if(user > computer) {
std::cout<< "The answer is lower. Try again.\n";
}
counter++;
guess(computer);
}

C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}