can you help me get rid of the errors? - c++

How do I get rid of these errors?Its supposed to calculate your age based on your birth year.
This code was made by me and my friend,both of us are begginers in programming.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofargs, char* pszArgs[]);
int CurrentYear = 2020;
int BirthYear;
cout << "Enter your birth year: "
cin >> BirthYear;
if (nBirthYear <= 0)
{
cout << "Birth year cannot be processed" <<endl;
BirthYear = 2020
}
else (BirthYear > 2020)
{
cout << "Birth year cannot be processed " <<endl;
BirthYear = 2020
}
if (nBirthYear < 2020)
(cout << "Your age is : " << CurrentYear - BirthYear <<endl;
)
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
these are the errors
||=== Build: Debug in Actualagefinder (compiler: GNU GCC Compiler) ===|
H:\c++\Actualagefinder\main.cpp|13|error: 'cout' does not name a type|
H:\c++\Actualagefinder\main.cpp|16|error: expected unqualified-id before 'if'|
H:\c++\Actualagefinder\main.cpp|21|error: expected unqualified-id before 'else'|
H:\c++\Actualagefinder\main.cpp|26|error: expected unqualified-id before 'if'|
H:\c++\Actualagefinder\main.cpp|28|error: expected unqualified-id before ')' token|
H:\c++\Actualagefinder\main.cpp|30|error: 'cin' does not name a type; did you mean 'main'?|
H:\c++\Actualagefinder\main.cpp|31|error: 'cin' does not name a type; did you mean 'main'?|
H:\c++\Actualagefinder\main.cpp|32|error: expected unqualified-id before 'return'|
||=== Build failed: 8 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

In C++, all executed code has to be within a function.
I.e. it should look like
int main(int nNumberofargs, char* pszArgs[])
{
/* code */
}
yours starts with a prototype, followed by orphaned code.
int main(int nNumberofargs, char* pszArgs[]);
/* code */
That is why the compiler complains that it expects a known type (for a declaration) where you have your code line starting with cout (which you not unreasonably expect to be already declared).
Other lines, which are not necessarily statements, can be local or global variable definititions, the latter being possible outside of functions. That is why the compiler does not complain about them.

The first issue you need to fix is the int main() declaration. By putting the semi-colon: int main(int nNumberofargs, char* pszArgs[]); you are telling the compiler that it has reached the end of the command, without doing anything. To fix this, like in your if statements, you must encapsulate everything in the after the declaration in curly braces.
Thus, your program becomes:
#include <cstdio>
#include <cstdlib>
#include <iostream>
int main(int nNumberofargs, char* pszArgs[])
{
// Put your stuff in curly braces
}
Your next bug is in your if statements. To put it simply, if statements don't work like that in C++.
Here is what if statements should be like:
if(something){
// Do something here
}
else if(something else){ // If there are more than one possible condition, use else if
// Do something else
}
else{ // If none other condition is satisfied
// Do something
}
Notice that you cannot have if twice (you can if you have nested if statements (like if statement inside if statement)
Those are the main problems in your program. The rest are small errors. For example, in many places a ; is missing. In other places, you call on undeclared variables:
if (nBirthYear < 2020) // This was probably a typo, nBirthYear is not declared
And in one place you have an ( which is a typo: (cout << "Your age is : " << CurrentYear - BirthYear <<endl;
Also, there is some unnecessary code, like the first two lines (they are not being used).
Nevertheless, here is a working version of your program:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofargs, char* pszArgs[]){
int CurrentYear = 2020;
int BirthYear;
cout << "Enter your birth year: " << endl;
cin >> BirthYear;
if (BirthYear <= 0)
{
cout << "Birth year cannot be processed" <<endl;
BirthYear = 2020;
}
else if(BirthYear > 2020)
{
cout << "Birth year cannot be processed " <<endl;
BirthYear = 2020;
}
else if (BirthYear < 2020){
cout << "Your age is : " << CurrentYear - BirthYear << endl;
}
cout << "Press Enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
As the comments said, it would be recommended to look again at whatever resources that you used to make this program, you must have your fundamentals down. Make sure that you know what every part of your programs do, and put comments to remind yourself in the future. I'll try to make this answer concise to help you understand, but you really should go back through what you've read.
Additionally, make sure that you're resources are relatively new, because a lot has changed in C++ since it was created.

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.

Code doesn't work as intended in visual c++ (examples from bjarne stroustrup programming and principles book 2n version)

Okey as I've recently started to read about C++ and try to go with the book I'm having Programming Principles and practice Using C++ 2nd version.
I'm a total newbie so this is probably why, but here goes.
Okey so in the book they have you implement a header .h file instead of the (iostream) etc. So it just have all those for the start as the book doesn't want us to focus on those libraries in the start of the learning.
So i implemented it and used it (not sure if this is related to the problem). Anyway at page 77, I'm getting stuck.
Basically it's a wrong value that's getting entered and it's supposed to just show -1(or 0) as the int gets a false value, etc Carlos(letters, not an integer) so the int doesn't get a correct value so the code that is supposed to work (and show 0 or -1 as it's an incorrect value that's entered) is this according to the book:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age\n";
string first_name = "???"; // string variable // ("???” means “don’t know the name”)
int age = –1; // integer variable (–1 means “don’t know the age”)
cin >> first_name >> age; // read a string followed by an integer
cout << "Hello, " << first_name << " (age " << age << ")\n";
}
and this is what i wrote:
#include "std_lib_facilities.h"
using namespace std;
int main()
{
cout << "Please enter your first name and age" << endl;
string First_Name = "???";
int Age = -1;
cin >> First_Name >> Age;
cout << "Hello, " << First_Name << "(age" << Age << ")" << endl;
keep_window_open();
return 0;
}
However, the result with visual c++ for me is a crash when i for example write 22 Carlos.
According to the book it's supposed to output Hello, 22 (age -1)
But for me it just crashes after i enter the word Carlos as value for age...
I don't get a a error or anything when i run and compile it, but it crashes after when i give the false value for age.
What am i doing wrong?
add: I know i can use a string to get it to work, however I'm just interested in why it doesn't work as I'm following this book i wish to follow it without having these kind of problems as it's intended to work.
Here is a gif when im doing it:
http://imgur.com/a/ERjhz
Solution: To use system("pause"); instead of keep_window_open();
however it's still annoying to read the book with the knowledge that the code in the book doesn't work always :(
Well it is isn't a problem but too fast to be noticed by our eyes.
i am adding the function definition of keep_window_open()
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
As you can see it simply takes the character input from the us
Forward you will learn about input stream and its buffer
So when you input a character in place of integer there is error flagged in the stream(background) and the only one of the characters input is used(in your case 'C' is used for flagging).
I am using input as Carlos 22
So now the input stream is still having characters 'a','r','l','o','s',22
so now the 'a' is used as a input for keep_window_open function
and the program ends without waiting for a input from you
So there is no error or crash but since the character is already there for input for keep_window_open function so its kind of really fast
The problem is in keep_window_open. It's a tricky function that is very hard to get absolutely right. You can replace it with this code that sidesteps the problem but only works on Windows:
inline void keep_window_open()
{
system("pause");
}
or with this slightly more complicated code that tries to take more cases into account:
inline void keep_window_open()
{
cout << "Please enter a character to exit\n";
if (!cin)
{
cin.clear();
cin.ignore(120, '\n');
}
char ch;
cin >> skipws >> ch;
}
(This assumes you don't enter lines longer than 120 characters. Replace 120 with numeric_limits<streamsize>::max() if you want it to be free from arbitrary limits. Other functions from std_lib_facilities.h do use 120 in this situation. You many or may not have to add #include <limits> directive to your program).
I have tested in a couple of cases and it appears to work with both correct and incorrect input to the program, but use it at your own risk. It still may or may not work correctly if your program requires more complicated input.
A good rule is to always except that the end users is idiots, so you need to write the program in a way that can handles all kinds of inputs without crashing. Therefore always read input numbers as std::string and then try convert it to int, short, double, unsigned int or what ever datatype you are using.
Your code should look like:
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
int main(int argc, char **argv)
{
int age;
std::string first_name;
std::string input_age;
std::cout << "Please enter your first name and age: " << std::endl;
std::cin >> first_name >> input_age; // Read the age as 'std::string'
try
{
age = std::stoi(input_age); // Try to convert age from 'std::string' to 'int'
std::cout << "Hello, " << first_name << " (" << age << ")" << std::endl;
}
catch(std::invalid_argument& ex) // 'std::stoi()' will throw 'std::invalid_argument' if it's not able to convert 'std::string' to 'int'
{
std::cerr << "Unable to convert input value ('" << input_age << "') to 'int'" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
catch(std::out_of_range& ex) // 'std::stoi()' will throw 'std::out_of_range' if 'std::string' is too small or too big to store in a 'int'
{
std::cerr << "The input value (" << input_age << ") is out of range, please input a value inside the range" << std::endl;
std::cerr << "Debug info: " << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}
So it's nothing to do with code, it's something to do with input.
when i for example write 22 Carlos.
The problem is that the code is asking for First_Name then Age, Not Age then First_Name. So when you put 22 for First_Name, the .exe got confused.
for example lets say I did this
int y = 0;
cout << "Give me INT: ";
cin >> y;
cout >> "You put: " >> y;
And when I run the program and put this for input
Give me INT: ghaisewofasd
*crashed*
This is a problem because the user is giving a string for when the code is asking for a int.
So for your case, instead of writing 22 Carlos, just write Carlos 22.
Also keep in mind, this book maybe not so correct, because it shouldn't print out Hello, (22). Now a days stuff like that crash if that happens, maybe it was a older version of C++.

2 errors on my simple block of code in a C++ file. error C2059: syntax error : '?'. 2nd IntelliSense: expected an expression. What is wrong?

#include <iostream>
#include <string>
using namespace std;
int main() {
int passes; //The number of passed classes
int fails; // The number of failed classes
double grade; //The current grade to be analyzed
//Initialize number of passes and fails
passes = 0;
fails = 0;
//Prompt for first grade
cout <<?Please enter a numeric grade(> 0) : ? :
cin >> grade;
return 0;
}
I'm not 100% sure what you've tried to achieve in the cout line, it looks pretty odd. Anyways, try to wrap the string you wish to print with quotes ("). After the cout, you should supply some parameters to the cout, you have no variable named '?', which is where the argument / string is supposed to be, and that's what the compiler points to when it prints the errors you receive.
I'd recommend printing 'std::endl' or '\n' in the end of your printed string so the cin would be in a different line.
This is what is it should look like
#include <iostream>
int main() {
int passes; //The number of passed classes
int fails; // The number of failed classes
double grade; //The current grade to be analyzed
//Initialize number of passes and fails
passes = 0;
fails = 0;
//Prompt for first grade
std::cout << " Please enter a numeric grade(> 0)" << std::endl;
std::cin >> grade;
std::cout << "Received grade is " << grade << std::endl;
return 0;
}

C++ ::: Cannot call error, as instructed to in Stroustrup's book

I have decided to take it upon myself to learn C++, I already have some experience with Java.
In Bjarne Stroustrup's Book he says:
Prompt the user to enter the age of the recipient and assign it to an
int variable age. Have your program write "I hear you just had a
birthday and You are 'age' years old." If age is 0 or less or 110 or
more, call error("you're kidding! ").
A few pages prior to that, he uses the error function as follows:
double d1 = 2.3;
double d2 = d1 + 2;
if (d1 < 0)
error( "d1 is negative");
When I try to run my program (Exercise from Bjarnes book), I get " Use of undeclared Identifier 'error' ".
I have tried to research my issue, which has yielded me a solution everytime until now, to no avail.
In case it is needed, here is the content of my Main.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Please enter the recipients name: " << endl;
string rname;
getline(cin, rname);
cout << "Ok, thank you. What is your mutual friends name: " <<endl;
string fname;
getline (cin, fname);
cout << "Ok, now what gender is you friends? 'm' for male, and 'f' for female: ";
char fsex;
cin >> fsex;
cout << "Fantastic, now how old is the recipient? " << endl;
int age;
cin >> age;
if(age >= 0 && age <= 110){
cout << "Thank you " << endl;
}
if(age <= 0 && age >= 110){
error("You're Kidding!");
}
return 0; }
You have to include header
std_lib_facilities.h
See the header definition
Here the error Use of undeclared Identifier 'error' means that you're trying to call a function called error, but the compiler has no idea where to find that function.
You need to declare and define that function somewhere, for example like this :
void error(char* str) {
puts(str);
}
Just like in Java, you can't use a function if it doesn't exist anywhere.

C++ argv[] not being passed fully

// Type the determine year in the command line as an argument.
// This program then prints the months and days for that year.
//Known Error argv[1] = the first digit of year,
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void printYear(int year);
int _tmain(int argc, char *argv[]){
string str;//varible used to exit the program
if (argc == 1 ){//checks to see if the years were inputted corrected
std::cout << "Please input Year in the command line. Exiting.." << std::endl;
cout << "Please type anything to continue..." << endl;
cin >> str;
return 1;
}
int Year = 1982;
int numYears = argc-1;
cout << "Number of Argments Loaded : " << numYears << endl;
for (int x = 1; x <= numYears; x++){
Year = atoi(argv[x]);
cout << "Year : " << argv[x] << endl;
cout << "Year is " << Year << endl;
printYear(Year);
}
cout << "Please type anything to continue..." << endl;
cin >> str;
return 0;
}
I'm currently learning C++ and this is one of my assignments. I just spent a better half of a day looking into this to no avail.
printYear() has been tested with numerous years and is functional. The only remanding error left is with argv[]. It only returns the first digit of the year inputted, which is fine if you want to research years 0-9. Any tips or trick you guys mind passing me? (I'm using Microsoft Visual Studio fyi)
Command line
calender.exe 1982
returns with
Number of Arguments Loaded : 1
Year : 1
Year is 1
Repetitive code I know but I'm troubleshooting.
The problem is _tmain. If you have unicode enabled it tries to give you wide (UTF-16) characters, so every other character will be \0. To fix this you want to call it main instead.
It seems that the arguments are passed as UNICODE strings however you process them in the program as ASCII strings.