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
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-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
sthsth
221k53 gold badges281 silver badges367 bronze badges
1
- 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.
|
|
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 —
|
|
You want to return the menu choice right? Ofc you do! You then have to return it like this —
return menuChoice;
Then in main —
|
|
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. Показов 4396. Ответов 8 Метки нет (Все метки)
У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять вот сам код
а вот ошибка 1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
0 |
Вездепух 10913 / 5909 / 1614 Регистрация: 18.10.2014 Сообщений: 14,851 |
|
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 секунд
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 |
|||
Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел
1 |
73 / 73 / 28 Регистрация: 06.10.2013 Сообщений: 309 |
|
28.10.2014, 18:45 |
6 |
Прогу не компилировала оно и видно) для 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 |
|||
спасибо успел сделать всё кажется пол часа назад , спасибо большое за то что предупредили что мой первый код было магко говоря бесполезным
0 |
zss Модератор 13252 / 10391 / 6213 Регистрация: 18.12.2011 Сообщений: 27,793 |
||||
28.10.2014, 19:09 |
9 |
|||
Решение
1 |
C++ C2059 Syntax Error ‘;’ — what does that mean??
I am stuck on this exercise for my C++ programming fundamentals class…
I am using visual studio 2017 and getting a C2059 Syntax Error ‘;’ Searching for this error gives examples of why the error could occur but all the examples are with something more complex than my simple code. The error points to line 18 (paycheck = . . . )
I’ve tried commenting out line 18, line 17+18, line 18+19, line 17-19, the entire program (really) but the error stays.
I also noticed that the error points to a file called exercise3_1.cpp while the file is actually name Exercise3_1.cpp (capitalized) and any other errors that get generated point to Exerise3_1.cpp
I’m so confused… please help.
#include "stdafx.h" #include <iomanip> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { ifstream inFile; ofstream outFile; inFile.open("inData.txt"); outFile.open("outData.txt"); string firstName, lastName, department; double salary, bonusRate, taxRate, distanceTraveled, timeTraveled, avgSpeed, coffeeCupCost, coffeeSalesAmount, paycheck; int coffeeCupsSold; inFile >> firstName >> lastName >> department >> salary >> bonusRate >> taxRate >> distanceTraveled >> timeTraveled >> coffeeCupsSold >> coffeeCupCost; paycheck = (salary * (1 + bonusRate / 100)) * (1 - (taxRate / 100)); avgSpeed = distanceTraveled / timeTraveled; coffeeSalesAmount = coffeeCupCost * coffeeCupsSold; outFile << setprecision(2) << fixed << "Name: " << firstName << " " << lastName << ", Department: " << department << endl << "Monthly Gross Salary: $" << salary << ", Monthly Bonus: " << bonusRate << "%, Taxes: " << taxRate << "%" << "Paycheck: " << paycheck << endl << endl << "Distance Traveled: " << distanceTraveled << " miles, Traveling Time: " << timeTraveled << " hours" << endl << "Average Speed: " << avgSpeed << " miles per hour" << endl << endl << "Number of Coffee Cups Sold: " << coffeeCupsSold << ", Cost: $" << coffeeCupCost << " per cup" << endl << "Sales Amount = $" << coffeeSalesAmount; return 0; }
edit: a couple words
Archived post. New comments cannot be posted and votes cannot be cast.