Ошибка c2059 синтаксическая ошибка return

Hey;
I’m kinda new to C++, but I’m getting a syntax error for my return statement in my function. Here’s my code:
// Physics Problem Solver.cpp : Defines the entry point for the console application.
//

#include «stdafx.h»
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <string.h>
#include <sstream>

void welcome();
int mainMenu();
void kinematics();
void dynamics();
void cmwe();
void motionAndWaves();

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    welcome();
    return 0;
}

//===========================================================================================================================================================================================================
//Functions
//===========================================================================================================================================================================================================
void welcome()
{
    cout << «Welcome to the Physics 20 Problem Solver. Please select your unit:» << endl;
    int menuSelection = mainMenu();
    system(«PAUSE»);
}
//===========================================================================================================================================================================================================
int mainMenu()
{
    int menuSelection = 1;
    char input = _getch();
    if (int(input) = 31)
        menuSelection++;
    if (int(input) = 30)
        menuSelection—;
    if (menuSelection < 1)
        menuSelection = 1;
    if (menuSelection > 4)
        menuSelection = 4;
    do
    {
        switch(menuSelection)
        {
        case 1:
            cout << «KINEMATICSnDynamicsnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

            case 2:
            cout << «KinematicsnDYNAMICSnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

                    case 3:
            cout << «KinematicsnDynamicsnCIRCULAR MOTION, WORK, AND ENERGYnOscillar Motion and Mechanical Waves» << endl;
            break;

            case 4:
            cout << «KinematicsnDynamicsnCircular Motion, Work, and EnergynOSCILLAR MOTION AND MECHANICAL WAVES» << endl;
            break;
        }
        while (int(input) != 13);
    }
    return menuSelection;
}

I don’t know why I’m getting this error, it’s the only return statement there. When I comment out the return line, I get a syntax error on my last curly brace. What’s wrong with the damn curly brace…I really don’t know. Been sitting here staring at it for an hour, this is the part of programming I hate.

Solved


When I try to compile this program i keep getting these errors:

(50) : error C2059: syntax error :
‘<=’

(50) : error C2143: syntax error
: missing ‘;’ before ‘{‘

(51) : error
C2059: syntax error : ‘>’

(51) : error
C2143: syntax error : missing ‘;’
before ‘{‘

(62) : error C2059: syntax
error : ‘else’

(62) : error C2143:
syntax error : missing ‘;’ before ‘{‘


#include <iostream>
#include <string>
#include <cassert>
using namespace std;

class income {
private:
    double incm;
    double subtract;
    double taxRate;
    double add;
    char status;
public:
    void setStatus ( char stats ) { status = stats; }
    void setIncm (double in ) { incm = in; }
    void setSubtract ( double sub ) { subtract = sub; }
    void setTaxRate ( double rate ) { taxRate = rate; }
    void setAdd ( double Add ) { add = Add; }

    char getStatus () { return status; }
    double getIncm () { return incm; }
    double getsubtract () { return subtract; }
    double getTaxRate () { return taxRate; }
    double getAdd () { return add; }
    void calcIncome ();
};

//calcIncome
int main () {
    income _new;
    double ajIncome = 0, _incm = 0;
    char status = ' ';
    bool done = false;
    while ( !done ) {
        cout << "Please enter your TAXABLE INCOME:n" << endl;
        cin >> _incm;
        if(cin.fail()) { cin.clear(); }
        if ( _incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
        if ( _incm > 0) { done = true; _new.setIncm(_incm); }
    }

    done = false;
    char stt [2] = " ";
    while ( !done ) {
        cout << "Please declare weather you are filing taxes jointly or single" << "n";
        cout << "t's' = singlent'm' = married" << endl;
        cin >> stt;
        if(cin.fail()) { cin.clear(); }
        if ( status == 's' || status == 'm' ) { done = true; _new.setStatus(stt[0]); }
        //if else { }
    }

    return 0;
};

This is part of a homework assignment so any pointers on bettering my programing would be **great**

Note:I am using Windows 7 with VS express C++ 2008

asked Jan 13, 2010 at 15:44

Wallter's user avatar

WallterWallter

4,2656 gold badges29 silver badges33 bronze badges

3

income is the name of your class. _incm is the name of your variable. Perhaps you meant this (notice the use of _incm not income):

if (_incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if (_incm > 0) { done = true; _new.setIncm(_incm); }

Frequently you use CamelCase for class names and lowercase for instance variable names. Since C++ is case-sensitive, they wouldn’t conflict each other if they use different case.

answered Jan 13, 2010 at 15:47

Jon-Eric's user avatar

Jon-EricJon-Eric

16.9k9 gold badges65 silver badges96 bronze badges

Your variable is named incom, not income. income refers to a type, so the compiler gets confused and you get a syntax error when you try to compare that type against a value in line 50.

One note for bettering you programming would be to use more distinct variable names to avoid such confusions… ;)

answered Jan 13, 2010 at 15:46

sth's user avatar

sthsth

221k53 gold badges281 silver badges367 bronze badges

1

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2059

Compiler Error C2059

03/26/2019

C2059

C2059

2be4eb39-3f37-4b32-8e8d-75835e07c78a

Compiler Error C2059

syntax error : ‘token’

The token caused a syntax error.

The following example generates an error message for the line that declares j.

// C2059e.cpp
// compile with: /c
// C2143 expected
// Error caused by the incorrect use of '*'.
   int j*; // C2059

To determine the cause of the error, examine not only the line that’s listed in the error message, but also the lines above it. If examining the lines yields no clue about the problem, try commenting out the line that’s listed in the error message and perhaps several lines above it.

If the error message occurs on a symbol that immediately follows a typedef variable, make sure that the variable is defined in the source code.

C2059 is raised when a preprocessor symbol name is re-used as an identifier. In the following example, the compiler sees DIGITS.ONE as the number 1, which is not valid as an enum element name:

#define ONE 1

enum class DIGITS {
    ZERO,
    ONE // error C2059
};

You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.

// C2059a.cpp
// compile with: /DTEST=
#include <stdio.h>

int main() {
   #ifdef TEST
      printf_s("nTEST defined %d", TEST);   // C2059
   #else
      printf_s("nTEST not defined");
   #endif
}

Another case in which C2059 can occur is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list—for example, one that used to initialize a structure—is not an expression. To resolve this problem, define a constructor to perform the required initialization.

The following example generates C2059:

// C2059b.cpp
// compile with: /c
struct ag_type {
   int a;
   float b;
   // Uncomment the following line to resolve.
   // ag_type(int aa, float bb) : a(aa), b(bb) {}
};

void func(ag_type arg = {5, 7.0});   // C2059
void func(ag_type arg = ag_type(5, 7.0));   // OK

C2059 can occur for an ill-formed cast.

The following sample generates C2059:

// C2059c.cpp
// compile with: /clr
using namespace System;
ref class From {};
ref class To : public From {};

int main() {
   From^ refbase = gcnew To();
   To^ refTo = safe_cast<To^>(From^);   // C2059
   To^ refTo2 = safe_cast<To^>(refbase);   // OK
}

C2059 can also occur if you attempt to create a namespace name that contains a period.

The following sample generates C2059:

// C2059d.cpp
// compile with: /c
namespace A.B {}   // C2059

// OK
namespace A  {
   namespace B {}
}

C2059 can occur when an operator that can qualify a name (::, ->, and .) must be followed by the keyword template, as shown in this example:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::Rebind<X>::Other AX; // error C2059
};

By default, C++ assumes that AY::Rebind isn’t a template; therefore, the following < is interpreted as a less-than sign. You must tell the compiler explicitly that Rebind is a template so that it can correctly parse the angle bracket. To correct this error, use the template keyword on the dependent type’s name, as shown here:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::template Rebind<X>::Other AX; // correct
};
  • Forum
  • Beginners
  • error C2059: syntax error : ‘return’

error C2059: syntax error : ‘return’

Hey guys, I’m relatively new to c++ , and I’m having trouble with my program I’m writing. It’s supposed to ask user input for squares and rectangles, but it’s not compiling right. Any kind of help or hints would be very much appreciated. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#include <iostream>
using namespace std;


void DisplayMenu()
{
    cout << "Main Menu" << endl << endl;
    cout << "1. Draw a square" << endl;
    cout << "2. Draw a rectangle" << endl;
    cout << "3. Quit the program" << endl;

}


int GetUserMenuChoice()
{
    int menuChoice = 0;

    do
    {
        DisplayMenu();
        cin >> menuChoice;

        if (menuChoice < 1 || menuChoice > 3)
        {
            cout << "Please enter a valid menu choice: ";
            cin >> menuChoice;
        }

        else
        {
            cout << "You entered: " << menuChoice << endl << endl;

        }
    }
    return;
}




int GetSize()
{
    int size = 0;

    do
    {
        cout << "Enter a size value from 1-10: ";
        cin >> size;

        if (size < 1 || size > 10)
        {
            cout << "Please enter a valid size value: ";
            cin >> size;
        }

        else
        {
            cout << "You entered: " << size << endl << endl;
        }
    }

    return;
}


int GetHeight()
{
    int height = 0;

    do
    {
        cout << "Enter a height value from 1-10: ";
        cin >> height;

        if (height < 1 || height > 10)
        {
            cout << "Please enter a valid height value: ";
            cin >> height;
        }

        else
        {
            cout << "You entered: " << height << endl << endl;
        }
    }

    return;
}

int GetWidth()
{
    int width = 0;

    do
    {

        cout << "Enter a width value from 1-10: ";
        cin >> width;

        if (width < 1 || width > 10)
        {
            cout << "Please enter a valid width value: ";
            cin >> width;
        }

        else
        {
            cout << "You entered: " << width << endl << endl;
        }

    }

    return;
}


void DisplaySquare(int size)
{
    {
        int row = 0;
        int col = 0;

        for (col = 1; col <= size; col++)
        {
            cout << endl << endl;

            for (row = 1; row <= size; row++)
            {
                cout << " * ";
            }
        }
        system("pause");


    }

}

void DisplayRectangle(int height, int width)
{
    {
        int row = 0;
        int col = 0;

        for (col = 1; col <= height; col++)
        {
            cout << endl << endl;

            for (row = 1; row <= width; row++)
            {
                cout << " * ";
            }
        }
        system("pause");

    }

}



int main()
{
    int menuChoice = 0, size = 0, height = 0, width = 0;


    while (menuChoice != 3)
    {
        menuChoice = GetUserMenuChoice();

        switch (menuChoice)
        {
        case 1:		// Draw a square
            size = GetSize();
            DisplaySquare(size);
            break;
        case 2:		// Draw a rectangle
            height = GetHeight();
            width = GetWidth();
            DisplayRectangle(height, width);
            break;
        case 3:		// Quit the program
            cout << "Quitting program!" << endl;
            break;
        }
    }

    return 0;
}

The errors I am getting are:
error C2059: syntax error : ‘return’
error C2059: syntax error : ‘return’
error C2059: syntax error : ‘return’

I’m not sure if I formatted the code right since it’s my first time posting here, I will fix it if it didn’t.

You never return anything in any of your functions. For example —

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int GetUserMenuChoice()
{
    int menuChoice = 0;

    do
    {
        DisplayMenu();
        cin >> menuChoice;

        if (menuChoice < 1 || menuChoice > 3)
        {
            cout << "Please enter a valid menu choice: ";
            cin >> menuChoice;
        }

        else
        {
            cout << "You entered: " << menuChoice << endl << endl;

        }
    }
    return;
}

You want to return the menu choice right? Ofc you do! You then have to return it like this —

return menuChoice;

Then in main —

1
2
3
menuChoice = GetUserMenuChoice();

switch (menuChoice)

If say, the user chooses menu option 2. menuChoice will be equal to 2. Which works fine :)

Oops, I forgot to type those in. I was in the middle of trying to figure it out.

I did however get the program to work. Just needed to get rid of the do {}, it was unnecessary.
Thanks for the help!

Glad it worked out :)

Topic archived. No new replies allowed.

BeyB

0 / 0 / 0

Регистрация: 28.10.2014

Сообщений: 23

1

28.10.2014, 17:52. Показов 4446. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять

вот сам код

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cmath>
#include <conio.h>
 
using namespace std;
int main()
 
{
    //Declare Variables
    double x, x1, x2, a, b, c;
 
    cout << "Input values of a, b, and c.";
    cin >> a >> b >> c;
 
    for (int i = 1; i <= 10; ++i);
    {
        if ((b * b - 4 * a * c) > 0)
            cout << "x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)" &&
            cout << "x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)";
 
        if else ((b * b - 4 * a * c) = 0)
            cout << "x = ((-b + sqrt(b * b - 4 * a * c)) / (2 * a)"
 
            if else ((b * b - 4 * a * c) < 0)
                cout << "x1 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)" &&
                cout << "x2 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)";
 
        _getch();
 
    }
 
 
    return (0);
 
}

а вот ошибка

1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
1> Исходный код.cpp
1>c:userspc hackerdocumentsvisual studio 2013projectsпроект3проект3исходный код.cpp(21): error C2059: синтаксическая ошибка: else
========== Сборка: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========



0



Вездепух

Эксперт CЭксперт С++

10946 / 5933 / 1624

Регистрация: 18.10.2014

Сообщений: 14,899

28.10.2014, 17:59

2

Что такое ‘if else’??? Это бессмысленная белиберда.

Очевидно имелось в виду ‘else if’…

Отдельно стоит заметить, что скорее всего от вас ожидали, что вы напечатаете сами решения квадратного уравнения, а не формулы для решения из учебника.

P.S. Ваша манера объединять последовательные выводы в ‘cout’ через оператор ‘&&’ остроумна, но вызывает удивление в коде у автора, который путает ‘if else’ с ‘esle if’.



0



5 / 5 / 5

Регистрация: 16.12.2013

Сообщений: 463

28.10.2014, 18:01

3

Что-то у вас тут не то. Во первых я вижу,что пропущена точка с запятой в 22 строке. Ну и если вы хотите,чтобы формулы записанные в cout работали,то их не нужно брать в кавычки.

Добавлено через 25 секунд
И надо писать else if



0



0 / 0 / 0

Регистрация: 28.10.2014

Сообщений: 23

28.10.2014, 18:12

 [ТС]

4

спасибо за помощь но я совсем уже запутался, мне надо собрать прогу которая должен решить дискриминант , а у мя Бог знает что получился , может поможете , обясните что к чему ?



0



Вероника99

5 / 5 / 5

Регистрация: 16.12.2013

Сообщений: 463

28.10.2014, 18:43

5

Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cmath>
#include <conio.h>
 
using namespace std;
int main()
 
{
    //Declare Variables
    double x=0, x1=0, x2=0, a, b, c;
 
    cout << "Input values of a, b, and c.";
    cin >> a >> b >> c;
 
    
        if ((b * b - 4 * a * c) > 0)
      {      x1=x2=(-b + sqrt((float)(b * b - 4 * a * c))) / (2 * a);
      cout<<" "<<x1<<x2<<endl;
 
        }
 
     else if((b * b - 4 * a * c) == 0)
 {            x=(-b + sqrt(abs((b * b - 4.0 * a * c)))) / (2 * a);
         cout<<" "<<x<<endl;
        }
         else if ((b * b - 4 * a * c) < 0)
            {   x1=x2=(-b + sqrt(abs((float)(b * b - 4 * a * c)))) * sqrt (abs((-1.0) / (2 * a)));
      cout<<" "<<x1<<endl;
    
     }
    
 
    return (0);
 
}



1



73 / 73 / 28

Регистрация: 06.10.2013

Сообщений: 309

28.10.2014, 18:45

6

Цитата
Сообщение от Вероника99
Посмотреть сообщение

Прогу не компилировала

оно и видно) для cin и cout нужна iostream, которой нет)



0



5 / 5 / 5

Регистрация: 16.12.2013

Сообщений: 463

28.10.2014, 18:46

7

О да,самое главное)))



0



BeyB

0 / 0 / 0

Регистрация: 28.10.2014

Сообщений: 23

28.10.2014, 19:03

 [ТС]

8

спасибо успел сделать всё кажется пол часа назад , спасибо большое за то что предупредили что мой первый код было магко говоря бесполезным

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    int x, y, s;
    cin >> x;
    cin >> y;
    s = x + y;
        cout << s;
        
        _getch();
 
        return 0;
 
}



0



zss

Модератор

Эксперт С++

13295 / 10431 / 6250

Регистрация: 18.12.2011

Сообщений: 27,866

28.10.2014, 19:09

9

Лучший ответ Сообщение было отмечено BeyB как решение

Решение

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
    cout << "Input values of a, b, and c.";
    double a, b, c;
    cin >> a >> b >> c;
     if(a==0)
    {
         if(b!=0)
         {
                double x=-c/b;
                cout<<" "<<x<<endl;
         }else
                cout<<" No solutionn";
        return 0;
    }
 
    double D=b * b - 4 * a * c;
    if (D>0)
    {     
         double x1=(-b + sqrt(D)) / (2. * a);
         double x2=(-b - sqrt(D)) / (2. * a);
         cout<<" "<<x1<<" "<<x2<<endl;
    }else 
    if(D == 0)
    {            
          x= -b / (2 * a);
          cout<<" "<<x<<endl;
    }else
          cout<<" No solutionn";
    return 0;    
}



1



Возможно, вам также будет интересно:

  • Ошибка c203f дэу нексия n150
  • Ошибка c2 14900 4 ps vita
  • Ошибка c2 12828 1 ps vita как исправить
  • Ошибка c1d22 форд мондео 4
  • Ошибка c1d00 форд фокус 3

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии