#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int NUM_GAME = 3;
int main ( void )
{
int score1 = 0;
int score2 = 0;
int score3 = 0;
int total = 0;
double average = 0;
char repeat;
string name, dummy;
//Allow user to run program again
do
{
//Resets total to process another game if desired
total = 0;
cout << "nBowler #1's name: ? "; //Reads name
getline(cin, name);
do
{
cout << "nEnter"<<name<<"'s score for each of the following games:";
cin >> score1;
cin >> score2;
cin >> score3;
if(score1 < 0 || score1 > 300 || score2 < 0 || score2 > 300 || score3 < 0 || score3 > 300 )
cout << "nn*** INVALID SCORE ENTERED! Please try again. ***";
while(score1 > -1 && score1 < 301 || score2 > -1 && score2 < 301 || score3 > -1 && score3 < 301);
total = score1 + score2 + score3;
}
cout << setprecision(2) << fixed << showpoint;
//Calcualtes the average sales for the salesperson
average = total / NUM_GAME;
cout << "nnThe bowling average for " << name << " is " << average << endl << endl;
cout << "nWould you like to calculate the average for another Game? Y or N ";
cin >> repeat;
getline(cin, dummy);
while (repeat == 'y' || repeat == 'Y');
}
return 0;
}
Please excuse the formatting issues and stuff its rough I know
this is coming up with 2 errors:
error C2061: syntax error : identifier 'cout'
error C2059: syntax error : 'return'
like I said it’s rough and the solution is probably something extremely obvious but I’m new and I’m still learning the ropes
Parker
8,52910 gold badges68 silver badges98 bronze badges
asked Oct 25, 2014 at 3:32
2
First of all, indent your code better.
Secondly,
do
{
while (repeat == 'y' || repeat == 'Y');
}
is probably not what you want.
answered Oct 25, 2014 at 3:39
ipavlipavl
82811 silver badges20 bronze badges
1
The do...while
should be
do
{
//code
}while(...);
Instead of
do
{
//code
while(...);
}
You have to close its body before the while
. So modify both your loops and then,the errors will be gone.
answered Oct 25, 2014 at 3:44
SpikatrixSpikatrix
20.2k7 gold badges37 silver badges83 bronze badges
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.
I’ve been looking at c++ for a while now, but all I have been able to do so far is basic console stuff. I wanted to do some more stuff so I started looking at SDL. I installed SDL no problem, but when I tried to follow this (http://pgdc.purdue.org/sdltutorial/01/) tutorial on SDL basics, the output from Visual Studio 2008 was:
|
|
I have no idea why it told me «return» was a syntax error and I had missing «;», having rechecked the whole code twice, and would appreciate any help in resolving my problems.
I’ve been looking at c++ for a while now, but all I have been able to do so far is basic console stuff. I wanted to do some more stuff so I started looking at SDL. I installed SDL no problem, but when I tried to follow this (http://pgdc.purdue.org/sdltutorial/01/) tutorial on SDL basics, the output from Visual Studio 2008 was:
|
|
I have no idea why it told me «return» was a syntax error and I had missing «;», having rechecked the whole code twice, and would appreciate any help in resolving my problems.
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.
I am extremely new to programming (my second week in) and I am trying to understand why when I start without debugging, I keep receiving this error message!
I only receive one error and it is the «c2059» ‘return’ error code.. It’s not descriptive at all, so I have no idea what I did wrong.
I have a picture link available below through google drive to show my code. Any help offered is greatly appreciated!
https://drive.google.com/file/d/0B5hXFZn11VsudXBXRlI3Vjg1OEU/view?usp=sharing
I am also fairly new to this site, if I am breaking any formal etiquette, please let me know as well..
I am using Microsoft Visual Studio 2008.
asked Feb 2, 2015 at 3:01
3
You have some stray text (endl/
) at the end of the second last line, which is causing a parsing error.
You also appear to have typed return o;
(the letter «o») — as you don’t have a variable called o
this will also cause an error. I suspect you meant return 0;
instead.
answered Feb 2, 2015 at 3:03
Jonathan PotterJonathan Potter
35.8k4 gold badges62 silver badges76 bronze badges
4
I am extremely new to programming (my second week in) and I am trying to understand why when I start without debugging, I keep receiving this error message!
I only receive one error and it is the «c2059» ‘return’ error code.. It’s not descriptive at all, so I have no idea what I did wrong.
I have a picture link available below through google drive to show my code. Any help offered is greatly appreciated!
https://drive.google.com/file/d/0B5hXFZn11VsudXBXRlI3Vjg1OEU/view?usp=sharing
I am also fairly new to this site, if I am breaking any formal etiquette, please let me know as well..
I am using Microsoft Visual Studio 2008.
asked Feb 2, 2015 at 3:01
3
You have some stray text (endl/
) at the end of the second last line, which is causing a parsing error.
You also appear to have typed return o;
(the letter «o») — as you don’t have a variable called o
this will also cause an error. I suspect you meant return 0;
instead.
answered Feb 2, 2015 at 3:03
Jonathan PotterJonathan Potter
35.8k4 gold badges62 silver badges76 bronze badges
4
knf 17 / 17 / 8 Регистрация: 18.09.2012 Сообщений: 184 |
||||
1 |
||||
Синтаксическая ошибка23.02.2013, 15:31. Показов 4949. Ответов 7 Метки нет (Все метки)
error C2059: синтаксическая ошибка: ]
__________________ 0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
23.02.2013, 15:31 |
7 |
The_bolT 73 / 73 / 12 Регистрация: 22.01.2013 Сообщений: 231 |
||||
23.02.2013, 15:33 |
2 |
|||
1 |
401 / 312 / 74 Регистрация: 17.03.2010 Сообщений: 1,119 |
|
23.02.2013, 15:35 |
3 |
0 |
knf 17 / 17 / 8 Регистрация: 18.09.2012 Сообщений: 184 |
||||||||||||
24.02.2013, 15:08 [ТС] |
4 |
|||||||||||
The_bolT, Получилось. Просто я уже убирал эти скобки и выдавало другую ошибку, а тут я написал так
а не
и получилось.. Добавлено через 23 часа 31 минуту
error C2059: синтаксическая ошибка: < 0 |
Каратель 6606 / 4025 / 401 Регистрация: 26.03.2010 Сообщений: 9,273 Записей в блоге: 1 |
|
24.02.2013, 15:15 |
5 |
Есть еще вопрос, не пойму где ошибки( компилятор же пишет в какой строке ошибка 0 |
17 / 17 / 8 Регистрация: 18.09.2012 Сообщений: 184 |
|
24.02.2013, 15:24 [ТС] |
6 |
Jupiter, 1>c:usersкомпdocumentsvisual studio 2010projects333.cpp(126): error C2059: синтаксическая ошибка: < Добавлено через 1 минуту Добавлено через 2 минуты Добавлено через 2 минуты 0 |
Заблокирован |
||||
24.02.2013, 15:26 |
7 |
|||
0 |
knf 17 / 17 / 8 Регистрация: 18.09.2012 Сообщений: 184 |
||||
24.02.2013, 16:37 [ТС] |
8 |
|||
Вот где Добавлено через 48 минут Добавлено через 9 минут 0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
24.02.2013, 16:37 |
Помогаю со студенческими работами здесь Синтаксическая ошибка!)) Синтаксическая ошибка #include <fstream>… Синтаксическая ошибка синтаксическая ошибка using namespace std;… Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 8 |
Software errors are prevalent. It’s easy to make them, and it’s hard to find them. In this chapter, we’ll explore topics related to the finding and removal of bugs within our C++ programs, including learning how sto use the integrated debugger that is part of our IDE.
Although debugging tools and techniques aren’t part of the C++ standard, learning to find and remove bugs in the programs you write is an extremely important part of being a successful programmer. Therefore, we’ll spend a bit of time covering such topics, so that as the programs you write become more complex, your ability to diagnose and remedy issues advances at a similar pace.
If you have experience from debugging programs in another compiled programming language, much of this will be familiar to you.
Syntax and semantic errors
Programming can be challenging, and C++ is somewhat of a quirky language. Put those two together, and there are a lot of ways to make mistakes. Errors generally fall into one of two categories: syntax errors, and semantic errors (logic errors).
A syntax error occurs when you write a statement that is not valid according to the grammar of the C++ language. This includes errors such as missing semicolons, using undeclared variables, mismatched parentheses or braces, etc… For example, the following program contains quite a few syntax errors:
#include <iostream>
int main()
{
std::cout < "Hi there"; << x << 'n'; // invalid operator (<), extraneous semicolon, undeclared variable (x)
return 0 // missing semicolon at end of statement
}
Fortunately, the compiler will generally catch syntax errors and generate warnings or errors, so you easily identify and fix the problem. Then it’s just a matter of compiling again until you get rid of all the errors.
Once your program is compiling correctly, getting it to actually produce the result(s) you want can be tricky. A semantic error occurs when a statement is syntactically valid, but does not do what the programmer intended.
Sometimes these will cause your program to crash, such as in the case of division by zero:
#include <iostream>
int main()
{
int a { 10 };
int b { 0 };
std::cout << a << " / " << b << " = " << a / b << 'n'; // division by 0 is undefined
return 0;
}
More often these will just produce the wrong value or behavior:
#include <iostream>
int main()
{
int x;
std::cout << x << 'n'; // Use of uninitialized variable leads to undefined result
return 0;
}
or
#include <iostream>
int add(int x, int y)
{
return x - y; // function is supposed to add, but it doesn't
}
int main()
{
std::cout << add(5, 3) << 'n'; // should produce 8, but produces 2
return 0;
}
or
#include <iostream>
int main()
{
return 0; // function returns here
std::cout << "Hello, world!n"; // so this never executes
}
Modern compilers have been getting better at detecting certain types of common semantic errors (e.g. use of an uninitialized variable). However, in most cases, the compiler will not be able to catch most of these types of problems, because the compiler is designed to enforce grammar, not intent.
In the above example, the errors are fairly easy to spot. But in most non-trivial programs, semantic errors are not easy to find by eyeballing the code. This is where debugging techniques can come in handy.
Добавлено 16 апреля 2021 в 20:18
В программном обеспечении распространены ошибки. Их легко сделать, а найти сложно. В этой главе мы рассмотрим темы, связанные с поиском и устранением ошибок в наших программах на C++, включая изучение того, как использовать интегрированный отладчик, который является частью нашей IDE.
Хотя инструменты и методы отладки не входят в стандарт C++, умение находить и устранять ошибки в программах, которые вы пишете, является чрезвычайно важной частью успешной работы программиста. Поэтому мы уделим немного времени рассмотрению этих тем, чтобы по мере усложнения программ, которые вы пишете, ваша способность диагностировать и устранять проблемы развивалась с той же скоростью.
Если у вас есть опыт отладки программ на другом компилируемом языке программирования, многое из этого будет вам знакомо.
Синтаксические и семантические ошибки
Программирование может быть сложной задачей, и C++ – довольно необычный язык. Сложите эти две вещи вместе и получите множество способов сделать ошибку. Ошибки обычно делятся на две категории: синтаксические ошибки и семантические ошибки (логические ошибки).
Синтаксическая ошибка возникает, когда вы пишете инструкцию, недопустимую в соответствии с грамматикой языка C++. Сюда входят такие ошибки, как отсутствие точек с запятой, использование необъявленных переменных, несоответствие круглых или фигурных скобок и т.д. Например, следующая программа содержит довольно много синтаксических ошибок:
#include <iostream>
int main()
{
std::cout < "Hi there"; << x; // недопустимый оператор (<), лишняя точка с запятой, необъявленная переменная (x)
return 0 // отсутствие точки с запятой в конце инструкции
}
К счастью, компилятор обычно перехватывает синтаксические ошибки и генерирует предупреждения или ошибки, поэтому вы легко обнаружите и устраните проблему. Затем просто снова попробуйте скомпилировать программу, пока не избавитесь от всех ошибок.
После того, как ваша программа скомпилировалась правильно, может быть непросто добиться от нее желаемого результата. Семантическая ошибка возникает, когда оператор синтаксически правильный, но не выполняет то, что задумал программист.
Иногда это приводит к сбою программы, например, в случае деления на ноль:
#include <iostream>
int main()
{
int a { 10 };
int b { 0 };
std::cout << a << " / " << b << " = " << a / b; // деление на 0 не определено
return 0;
}
Чаще всего они просто приводят к неправильному значению или поведению:
#include <iostream>
int main()
{
int x;
std::cout << x; // Использование неинициализированной переменной приводит к неопределенному результату
return 0;
}
или же
#include <iostream>
int add(int x, int y)
{
return x - y; // функция должна складывать, но это не так
}
int main()
{
std::cout << add(5, 3); // должен выдать 8, но выдаст 2
return 0;
}
или же
#include <iostream>
int main()
{
return 0; // функция завершается здесь
std::cout << "Hello, world!"; // поэтому это никогда не выполняется
}
Современные компиляторы стали лучше обнаруживать определенные типы распространенных семантических ошибок (например, использование неинициализированной переменной). Однако в большинстве случаев компилятор не сможет отловить большинство из этих типов проблем, потому что компилятор предназначен для обеспечения соблюдения грамматики, а не намерений.
В приведенных выше примерах ошибки довольно легко обнаружить. Но в большинстве нетривиальных программ, взглянув на код, семантические ошибки найти нелегко. Здесь могут пригодиться методы отладки.
Теги
C++ / CppDebugLearnCppДля начинающихОбучениеОтладкаПрограммирование
I’m working on this project and I’m REALLY close, I’m just gettin a C2059 error and I have no idea why?
#include <iostream>
using namespace std;
int main()
{
int guess;
int die;
float total = 10;
char ans;
cout << "Welcome to Dice Roll!" << endl;
cout << "Your bank total is: $" << total << ".00" << endl;
cout << "nGuess the next roll! It costs $1.00 to play!" << endl;
cout << "The correct guess nets you $100.00!n" << endl;
cin >> guess;
do
{
--total;
die = (int)(rand() % 6) + 1;
if(guess < 1 || guess > 6)
{
cout << "Invalid Input" << endl;
cout << "Try again? (Type 'Y' or 'N')" << endl;
cin >> ans;
}
if(guess == die)
{
cout << "Congratulations! The dice rolled a" << die << "You won $100.00!" << endl;
cout << "nYour bank total is: $" << total + 100 << ".00" << endl;
cout << "Try again? (Type 'Y' or 'N')" << endl;
cin >> ans;
}
if (guess != die)
{
cout << "I'm sorry, but you lost and we now have your dollar." << endl;
cout << "nYour bank total is: $" << total << ".00" << endl;
cout << "Try again? (Type 'Y' or 'N')" << endl;
cin >> ans;
} while(ans == 'Y' || 'y');
if (ans != 'Y' || ans != 'y' || ans != 'N' || ans != 'n')
{
cout << "Invalid Input" << endl;
}
else
{
cout << "Thanks for playing! Your bank is $" << total << ".00" << endl;
}
}
return 0;
}
1>Compiling...
1>Lab9.cpp
1>c:usersstephon.stephon-pcdocumentsvisual studio 2008projectslab9lab9lab9.cpp(51) : error C2059: syntax error : 'return'