i keep get this "error C2059" C++ - c++

I am getting this error
error C2059: syntax error : 'if'
This is my code
// N.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
int main ()
{
int x,y,n,i,m;
std::cout<<"please enter a number";
i=0;
std::cin>>n;
for (x=1;x=n;x++)
for (y=1;y=n;y++)
if (x=y) m=x;
else;
while (x!=y) ;
do
{
if (x>y) x=x-y;
else y=y-x;
m=x;
}
if (m=1) i=i+1;
std::cout<<i;
return 0;
}
what is the problem ?
I am using microsoft visual studio 2008

The problem is that after the do { ... } the compiler is expecting a condition:
do
{
if (x>y) x=x-y;
else y=y-x;
m=x;
} while (condition);
In addition, your code seems to be not correct at all. For instance, your if (x=y) condition may be like this: if (x==y), and other...

You have errors in your for statements.
Use == for comparison, not = which is assignment.
Also, use < or <= as comparison. The == condition may be skipped over in loops.
A suggestion to help prevent these issues in the future: Use '{' and '}' with for, if, else and while.
For example:
for (x=1;x=n;x++)
{ // Insert this line.
for (y=1;y=n;y++)
{ // Insert this line.
if (x=y)
{
m=x;
}
else
{
;
}
} // End of for y
} // End of for x
The braces and indentation help spot errors during code reviews. Most coding styles demand the braces, even for single statements.
Also, use spaces to make code more readable. They don't impact the build time or code generation, but really help when reading the code:
for (x = 1; x <= n; x++)

Related

Error in C++ program (*** Error in `./a.out': free(): invalid pointer: 0x00000000024a1c4f ***)

i'm writing a simple program in C++, however i keep getting the error described in the title. I have searched the internet, but the questions and answers i find usually involve templates. When i run the program on the clang compiler it simply stops without executing the function (marked in the code), but when i ran it on the online gdb debugger i was able to identify the error, however, i don't know what is causing it. I commented the function i think is causing the issue on the code.
Any help is much appreciated!
The code:
#include "iostream"
#include "string"
#include "vector"
#include "algorithm"
#include "utility"
#include "cmath"
class Parser{
private:
std::vector<char> input_c;
std::vector<std::pair<std::string, char>> assigned_pairs;
std::vector<double> multi_values;
public:
void extract_multis(){ /*STOPPED IN THIS FUNCTION */
for(int i = 0; i < input_c.size(); i++){
if(get_type(input_c[i-1]) == "multi"){
std::cout<<input_c[i]<<'\n';
multi_values.push_back(std::strtod(&input_c[i],NULL));
}
}
for(auto i : multi_values){
std::cout<<"multi values: "<<i<<'\n';
}
}
std::string get_type(char x){
std::vector<std::pair<std::string, char>>::iterator ll;
for(ll = assigned_pairs.begin();ll != assigned_pairs.end(); ll++){
if( ll->second == x){
return ll->first;
}
}
}
void show_pairs(){
std::vector<std::pair<std::string, char>>::iterator ll;
for(ll = assigned_pairs.begin(); ll != assigned_pairs.end();ll ++){
std::cout<<ll->first<<'\t'<<ll->second<<'\n';
}
}
void define_types(std::vector<char> y){
for(int i = 0; i < y.size(); i++){
switch(y[i]){
case '+':
assigned_pairs.push_back(std::make_pair("sum",y[i]));
break;
case '*':
assigned_pairs.push_back(std::make_pair("multi",y[i]));
break;
case '-':
assigned_pairs.push_back(std::make_pair("sub",y[i]));
break;
case '/':
assigned_pairs.push_back(std::make_pair("div",y[i]));
default:
assigned_pairs.push_back(std::make_pair("term", y[i]));
}
}
}
void tokenize(std::string x){
for(auto i : x){
input_c.push_back(i);
}
define_types(input_c);
show_pairs();
extract_multis();
}
};
int main(int argc, char** argv){
Parser larry;
const std::string input = "4*3+1+2*5*6";
larry.tokenize(input);
}
There are several bugs in the shown code.
for(int i = 0; i < input_c.size(); i++){
if(get_type(input_c[i-1]) == "multi"){
On the first iteration of the loop i will be 0, the beginning value. The if statement's condition will then try to evaluate input_c[-1] which is undefined behavior.
std::string get_type(char x){
// ...
}
If the loop in this function fails to find a match, and ends, this function reaches an end without returning a std::string.
This is also undefined behavior, and all modern C++ compilers will issue a warning about this common programming error. If yours didn't you should consider updating your compiler. If yours did you should always attempt to fix all messages that your compiler is producing, even if the compiler still manages to produce compiled code. Your compiler is reporting a likely bug in the code, like the one here.
These are the obvious bugs in the shown code. There could be less obvious ones, but before getting there you will need to fix these major bugs, first.

Small program to calculate prime numbers not working

Upon completion this program will output all prime numbers up to 1000, it is a fairly simple program and although I have read and re-read over the syntax many times at this point it is still not working
The code has been edited since the original post, it now runs with 0 errors, however it will not display the correct result, instead it displays 008D1389 over and over again.
this is the code in its entirety:
#include <iostream>
using namespace std;
//funtion prototypes
int output_number, number = 1, value = 1, i;
bool is_this_number_prime(int number_in_question);
bool does_it_have_factors(int numerator, int denominator);
int prime_number_sender();
int prime_number_output();
//function definitions
int prime_number_output()
{
int value;
value = prime_number_sender();
return value;
}
int prime_number_sender()
{
int value = number;
if (is_this_number_prime(number) == true)
return value;
else
return 0;
}
bool is_this_number_prime(int number_in_question)
{
bool answer = true;
int i;
for (i = 2; i <= number; i++)
{
if (does_it_have_factors(number, i) == true)
answer = false;
}
return answer;
}
bool does_it_have_factors(int numerator, int denominator)
{
bool result = false;
if (numerator % denominator == 0){
bool result = true;
}
return result;
}
int main() {
bool is_this_number_prime(int number_in_question);
bool does_it_have_factors(int numerator, int denominator);
int prime_number_sender(int number_in_question);
int prime_number_output();
int output_number = prime_number_output();
int i;
for (i = 2; i <= 1000; i++)
{
cout << prime_number_output << endl;
number++;
}
return 0;
}
If anyone can shed any light as to why the code is not working I will be extremely grateful. Thankyou.
Your code is generating quite a few errors for me.
main.cpp|48|error: too few arguments to function 'int prime_output(int)'|
You have prime_output declared as int prime_output(int value) but you promptly shadow the parameter value with a local variable value. You might as well drop the parameter, it's not doing you any good.
main.cpp|52|error: too few arguments to function 'int perfect_output(int)'|
Same issue as above. It looks like you're trying to modify the parameter directly, though, which is a no-no the way you're doing it. Try using a reference:
int perfect_output(int& value)
The function itself is weird as heck though. You don't output anything or do any calculations. I feel like you may not have finished writing that yet.
main.cpp||In function 'void user_selection()':|
main.cpp|59|error: a function-definition is not allowed here before '{' token|
This is probably where you're getting the error your question mentions. Your formatting makes it difficult to see this directly; fortunately Code::Blocks tells me where the problem is.
void user_selection()
{
You never close this. (More accurately, your closing brace is all the way at the end of the file, where it triggers another mismatch error.)
main.cpp|87|error: expected declaration before '}' token|
See above. This is the closing brace that somehow got detached from user_selection. Try to be more careful with your code formatting; the easier you can read it, the easier you can see things like this before the compiler does.
main.cpp|63|error: expected primary-expression before '<' token|
Your if statement is formatted oddly. Change = < to <= like this:
for (i = 2; i <= 1000; i++)//if numbers are 1 off, make i = 1.

Taking in array of unknown size in c++

Ok I am extremely new to programming, and I am taking a c++ class. Basically for the current project I have to take in an array of unknown size, resize it, and output a bunch of statistics like average, Q1, Q3, etc. I am having trouble taking in the array from the user. I need to quit taking in variables once they enter 0. Here is what I have:
int i = 1; //When I first posted this I didn't mean to comment out the '= 1' part
do {
cin >> array[i];
if (array[i] != 0)
return true;
} while (true);
What am I doing wrong? the program stops after I enter 1 number every time no matter what number I enter.
I am using vector class btw.
Do the following:
// change int to your type
int val;
std::vector<int> vec;
while(std::cin >> val) {
if(val == 0) break;
vec.push_back(val);
}
Reason: Stating a return clause causes to exit the loop.
use of std::vector ensures the arbitrary size condition.
Update after #nonsensickle's constructive remark:
The following piece of code also ensures the only 0 terminates input process condition:
// change int to your type
int val;
std::vector<int> vec;
do {
if(std::cin >> val) {
if(val == 0) break;
vec.push_back(val);
} else { // fix broken input stream in case of bad input
std::cin.clear();
std::cin.ignore(1,'\n');
}
} while(true);
and a more sophisticated way, although overkill but what the hell :), with templates and type traits:
template <typename T>
struct zero_traits
{
static T getzero() { return T(0); }
};
template <>
struct zero_traits<std::string>
{
static std::string getzero() { return "0"; }
};
template <>
struct zero_traits<char>
{
static char getzero() { return '0'; }
};
template <typename T>
std::vector<T> read_values()
{
T val;
std::vector<T> vec;
do {
if(std::cin >> val) {
if(val == zero_traits<T>::getzero()) break;
vec.push_back(val);
} else {
std::cin.clear();
std::cin.ignore(1,'\n');
}
} while(true);
return vec;
}
int main()
{
// change int to your type
std::vector<int> vec = read_values<int>();
for(auto i : vec) std::cout << i << std::endl;
}
First of all i will never increment.
Second of all, if (array[i] != 0) will return if that array's value doesn't equal 0.
You need to read into how do { ... } while() loops work as well as what return statements do. Might as well throw in how to increment an array while you're at it.
I will not try to answer your question directly. What you have is a small logic error and a misunderstanding of the do {...} while () looping construct. What you need is to learn how to step through your code.
Let's go through your code line by line (there are only 6 lines here so it should be really easy):
int i; - Ok, so we are declaring an integer i here but are not giving it a value. As such, i can have a random value.
do { - This is where we will come back to when we evaluate the while clause. But only if the result of the while clause is true.
cin >> array[i] - Store a value that the user enters in the array at the position i. Here we ask ourselves a question, what is i? We should know its value without having to run the program. Hint: there's a problem here because of i
if (array[i] != 0) - If the number entered by the user is not zero return true (exit this function with the result true).
} while (true); - Go back to the do { line and redo all the steps until you get here. There is no condition here so it will keep happening until we exit this function.
Hint: The only exit point of your loop is at step 4.
With this, you should be able to figure out your problem. Trying to break down the problem for yourself should be your first step.
I recommend reading this blog post on debugging small programs. It should be informative.
Though code posted by others (in particular #DimitriosBouzas) will work, and is the better choice, I strongly recommend fixing your code and learning why it failed. This will help you in the long run more than #DimitriosBouzas' elegant solution.
Before answering your question.
Initialize your variables int i=0; .You assign i to be zero because arrays are zero indexed.
You have to incerement i. If do not increment it, i will point at the first "bucket" in your array the whole time. Use i++ or i = i + 1 after every iteration of the do while loop to move "forward" in your array.
You want your program to run until zero is entered so you have to write your condition like this if (array[i] == 0) return true;. This condition is true when the last number entered was zero and it will cause your method to return. It would be more elegant for you to check for it in the while clause.
Putting it all together, your code should look like this
int i=0;
do {
cin >> array[i];
if (array[i] != 0) break;
i++;
} while (i < maxSize);
//do stuff with filled array

error C2601: 'main' : local function definitions are illegall - MS VS 2013 Compiler

I'm writing a small program in C++. When I try to compile it using MS VS 2013 Compiler I get an error: "C2601: 'main' : local function definitions are illegall". What does it mean? My code is:
#include <iostream>
int n;
int pomocniczaLiczba;
using namespace std;
int ciong(int n){
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
int main()
{
cin >> n;
cout >> ciong(n);
return 0;
}
}
Your bracketing is broken. The net result is that you are attempting to define your main function inside ciong. And C++ does not support nested function definitions. Hence the compiler error.
The code should be:
#include "stdafx.h"
#include <iostream>
using namespace std;
int ciong(int n)
{
switch (n)
{
case 1:
return 1;
break;
case 2:
return 2;
break;
default:
int pomocniczaLiczba = ciong(n - 2) + ciong(n - 1) * ciong(n - 1);
return pomocniczaLiczba;
break;
}
} // <----- Oops, this was missing in your code
int main()
{
int n;
cin >> n;
cout << ciong(n) << endl;
return 0;
}
And there are other bugs. For example, you meant cout << ciong(n).
Using Visual Studio 2013 C++, I got compilation errors that I couldn't explain.
The compilation errors were:
*main.cpp(325): error C2601: 'FLAG' : local function definitions are illegal
main.cpp(323): this line contains a '{' which has not yet been matched
main.cpp(326): fatal error C1075: end of file found before the left brace '{' at 'main.cpp(323)' was matched*
But there was nothing wrong with my code. I counted all brackets and the number matched. There weren't any function inside another function.
I solved it by removing all "//" comments from the source code. It seems that the reason for that is bad line formatting which causes the compiler to miss a line break, so the line after a comment is treated as a comment as well.
For example:
// This is a comment
This_is_a_line;
is treated as:
// This is a comment This_is_a_line;
There are many posts of the net about similar problems and some even suggested that they could be caused by a memory (RAM) fault on the machine, so before you replace your RAM, just remove the comments and see...
Michael Haephrati מיכאל האפרתי

switch between if/else blocks on error

I'm looking for a way to switch between an if and an else block when an error occurs. For example:
cout << "Enter 1 or 2 as your choice...";
cin >> choice;
if(choice==1) {
//do something here
//if error occurs....
} else if(choice==2) {
//switch to this else block
}
I've played around with try/throw/catch but it appears that the catch has to follow the try statement. Any ideas/suggestions would be appreciated!
When I come across this situation, I create a separate function with the code wanted in the else block. Then I call the function whenever needed (if an error occurs, and in the else block).
Looks like you could just not have an "else":
int error = 0;
if( choice==1 ) {
// Something happens
error = 1;
}
if( error == 1 || choice == 2 ) {
// Do things
}
You really want to split that in to two different conditional blocks. After all, you don't really mean "else".
if(choice==1)
{
//if error occurs....
}
if(choice==2 || error)
{
//switch to this block
}