In a header file, I want to declare a short function
Rotate(array, degree), which would rotate an array of elements by some degree:
for example, if my array contains {1, 2, 3, 4, 5}, and the rotation degree is 2, then the modified array should be {4, 5, 1, 2, 3}.
My code is as follows:
#ifndef ROTATE_ARRAY_H
#define ROTATE_ARRAY_H
void Rotate(std::vector<int>& array, const int rotation_degree);
#endif // ROTATE_ARRAY_H
Now this short header file gives «expected primary expression before const»
on the line, where void is declared.
Note that if I remove vector from the function argument list, then
void Rotate(const int rotation_degree);
compiles successfully (but of course does not work as expected). So I believe, the problem is something to do with the vector.
Please bare in mind that this is a header file, and no code like
include<vector>;
using namespace std;
is allowed, as that would violate the style guide.
So the question is: how to get rid of «expected primary expression before const» error?
Thanks for your help in advance.
- Forum
- Beginners
- expected primary-expression before «cons
expected primary-expression before «const» c++
Trying to figure out why i am getting this error:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
const double g-v = 125.00,
const double p-v = 145.00,
const double l-v = 180.00;
char g,
p,
l,
v;
double room_type,
rate,
frig,
bed,
gt;
int days;
//Get information from the user
cout << setprecision(2)
<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint);
cout << «Enter your room type (‘g’ for garden view, ‘p’ for pool view, or ‘l’ for lake view: «;
cin.get();
room_type = cin.get();
cout << «Enter your number of day you stayed: «;
cin >> days;
cout << «Did you have a refrigerator (y/n): «;
cin.get();
frig = cin.get();
cout << «Did you have an extra bed (y/n): «;
cin.get();
bed = cin.get();
//Calculate and output the results
if (room_type = ‘g’)
rate = g-v * days;
if (room_type = ‘p’)
rate = p-v * days;
if (room_type = ‘l’)
rate = l-v * days;
if (frig = ‘y’)
frig = days * 2.5;
else
frig = 0;
if (bed = ‘y’)
bed = days * 15.00;
else
bed = 0;
gt = rate + frig + bed;
//output the results
cout << «The room type you stayed in was the: » << setw(14) << room_type << endl;
cout << «The number of days you stayed was: » << setw(14) << days << endl;
cout << «Your basic room rate was: » << setw(14) << rate << endl;
cout << «Your charge for a refrigerator was: » << setw(14) << frig << endl;
cout << «Your charge for an extra bed was: » << setw(14) << bed << endl;
cout << «Your total charge for the stay is: » << setw(14) << gt << endl;
return 0;
}
In your variable declarations, you are using ,
instead of ;
. It’s saying that after the comma, it expects another variable name rather than another type name.
For example, you can:
|
|
Also, you cannot use a minus in a variable name, for obvious reasons.
thanks got it worked out. now to work on the calculations and output.
output is good, any suggestions on the calculations?
Topic archived. No new replies allowed.
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||
1 |
||||
13.07.2016, 02:08. Показов 13571. Ответов 20 Метки нет (Все метки)
Ошибка такая…11 19 E:Новая папкаDev-CppPracticeЧто-то пробую2.cpp [Error] expected primary-expression before ‘char’ Добавлено через 1 минуту
__________________
0 |
Заблокирован |
|
13.07.2016, 02:10 |
2 |
login[80]; Это массив чего? Добавлено через 59 секунд
loginANDpassword(char*); А в этот вызов что передается? Добавлено через 35 секунд
bool login(); Это не вызов функции.
0 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||||||
13.07.2016, 02:15 [ТС] |
3 |
|||||||
nimazzzy, Это массив Указателя. Ибо если написать
Тогда не работает. А так хоть одна ошибка. Добавлено через 4 минуты
Что еще не ясно
0 |
DrOffset 16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
||||||||
13.07.2016, 02:46 |
4 |
|||||||
Что еще не ясно Я думаю ему все ясно. Он пытался задать тебе наводящие вопросы, чтобы ты исправил код. Кликните здесь для просмотра всего текста
Добавлено через 2 минуты
Это массив Указателя. Ибо если написать
Тогда не работает. А так хоть одна ошибка. Вообще это называется «замаскировал проблему». Количество ошибок вообще не показатель. У тебя может быть их 40 из-за одной строчки кода (по цепочке). Или может быть внешне одна ошибка, а ее исправление приведет ко второй и так до одурения.
0 |
0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
|
13.07.2016, 02:47 [ТС] |
5 |
nimazzzy, я чет не совсем понял, что ты сделал. Ты добавил константу? а объясни пожалуйста что изменилось.. я вижу что прога заработала. Помоги справиться с этим..
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
13.07.2016, 02:50 |
6 |
Adamtotu, сделал не он, а я. И я отметил восклицательными знаками то, что исправил. В частности то, на что обратил внимание товарищ nimazzzy в своем сообщении.
0 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||||||
13.07.2016, 02:56 [ТС] |
7 |
|||||||
Спасиб…сейчас посмотрю Добавлено через 4 минуты
0 |
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
13.07.2016, 12:53 |
8 |
Сообщение было отмечено Adamtotu как решение Решение
Зачем было вводить этот массив? Ну тебе ведь нужно куда-то сохранять введенный логин.
Почему здесь просто login, почему без Амперсанта? Потому что у нас уже есть указатель (параметр функции), который содержит адрес первого элемента массива arrlogin.
1 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||||||
14.07.2016, 01:23 [ТС] |
9 |
|||||||
DrOffset, спасибо)) лайк помог Добавлено через 35 минут
после усовершенствования..
E:Новая папкаDev-CppPracticeЧто-то пробую2(1.1).cpp In function ‘void menu()’:
0 |
Заблокирован |
|
14.07.2016, 01:30 |
10 |
case 1:loginANDpassword(char* login, char* password); Зачем объявлять типы аргументов при вызове функции?
0 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||
14.07.2016, 01:33 [ТС] |
11 |
|||
nimazzzy, если не объявлять тогда смотри что получается..
E:Новая папкаDev-CppPracticedddd.cpp In function ‘void menu()’:
0 |
Заблокирован |
|
14.07.2016, 01:36 |
12 |
Ты убрал не только типы, но и сами аргументы.
0 |
0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
|
14.07.2016, 01:37 [ТС] |
13 |
nimazzzy, покажи как нужно написать, если не трудно
0 |
Заблокирован |
|
14.07.2016, 01:40 |
14 |
Мне не трудно, но я предпочту подождать, пока ты соизволишь немного разобраться с синтаксисом языка. Тем более, что примеры правильных вызовов у тебя есть.
1 |
0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
|
14.07.2016, 01:43 [ТС] |
15 |
nimazzzy, Не знаю, не знаю. Я дошел до темы указатели. Я практикуюсь. Пытаюсь сделать то что в моих силах. Это мне не понятно, поэтому и обращаюсь на форум, ибо здесь могут помочь с такими проблемами.
0 |
Заблокирован |
|
14.07.2016, 10:12 |
16 |
Тебе самому не кажется странным, что у тебе в коде есть вызов
loginANDpassword(arrlogin,arrPassword); , а сейчас ты пытаешься сделать
loginANDpassword(char* login, char* password);
loginANDpassword(); Почему все так по-разному? Даже с точки зрения логики, а не языка… Добавлено через 32 секунды
Я дошел до темы указатели. Надо пройти тему функции.
0 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||
14.07.2016, 16:29 [ТС] |
17 |
|||
nimazzzy, Так ты и не ответил ..
0 |
Заблокирован |
|
14.07.2016, 22:29 |
18 |
Передай функции 2 аргумента, как у тебя уже есть в коде.
Так ты и не ответил .. Да, я хочу, чтобы ты понял. Добавлено через 5 часов 42 минуты
bool loginANDpassword_check(char const* login,char const* password); То есть, она принимает два параметра. Если убрать исходный код, то что ты человеческим языком хочешь в эту функцию передать? И где это «что-то» в функции menu, из которой идет вызов?
0 |
Adamtotu 0 / 0 / 0 Регистрация: 12.05.2016 Сообщений: 41 |
||||
14.07.2016, 22:55 [ТС] |
19 |
|||
nimazzzy,
0 |
Заблокирован |
|
14.07.2016, 23:28 |
20 |
Есть exit.
1 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
14.07.2016, 23:28 |
20 |
The expected primary expression before occurs due to syntax errors. It usually has a character or a keyword at the end that clarifies the cause. Here you’ll get access to the most common syntax mistakes that throw the same error.
Continue reading to see where you might be getting wrong and how you can solve the issue.
Contents
- Why Does the Expected Primary Expression Before Occur?
- – You Are Specifying the Data Type With Function Argument
- – The Wrong Type of Arguments
- – Issue With the Curly Braces Resulting in Expected Primary Expression Before }
- – The Parenthesis Following the If Statement Don’t Contain an Expression
- How To Fix the Given Error?
- – Remove the Data Type That Precedes the Function Argument
- – Pass the Arguments of the Expected Data Type
- – Ensure The Equal Number of Opening and Closing Curly Brackets
- – Add an Expression in the If Statement Parenthesis
- FAQ
- – What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
- – What Is a Primary Expression in C Language?
- – What Are the Types of Expressions?
- Conclusion
Why Does the Expected Primary Expression Before Occur?
The expected primary expression before error occurs when your code doesn’t follow the correct syntax. The mistakes pointed out below are the ones that often take place when you are new to programming. However, a programmer in hurry might make the same mistakes.
So, here you go:
– You Are Specifying the Data Type With Function Argument
If your function call contains the data type along with the argument, then you’ll get an error.
Here is the problematic function call:
int addFunction(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
int main()
{
int result = addFunction(int 20, int 30);
}
– The Wrong Type of Arguments
Passing the wrong types of arguments can result in the same error. You can not pass a string to a function that accepts an argument of int data type.
int main()
{
int result = addFunction(string “cat”, string “kitten”);
}
– Issue With the Curly Braces Resulting in Expected Primary Expression Before }
Missing a curly bracket or adding an extra curly bracket usually results in the mentioned error.
– The Parenthesis Following the If Statement Don’t Contain an Expression
If the parenthesis in front of the if statement doesn’t contain an expression or the result of an expression, then the code won’t run properly. Consequently, you’ll get the stated error.
How To Fix the Given Error?
You can fix the “expected primary-expression before” error by using the solutions given below:
– Remove the Data Type That Precedes the Function Argument
Remove the data type from the parenthesis while calling a function to solve the error. Here is the correct way to call a function:
int main()
{
int result = addFunction(30, 90);
}
– Pass the Arguments of the Expected Data Type
Double-check the function definition and pass the arguments of the type that matches the data type of the parameters. It will ensure that you pass the correct arguments and kick away the error.
– Ensure The Equal Number of Opening and Closing Curly Brackets
Your program must contain an equal number of opening and closing curly brackets. Begin with carefully observing your code to see where you are doing the mistake.
– Add an Expression in the If Statement Parenthesis
The data inside the parenthesis following the if statement should be either an expression or the result of an expression. Even adding either true or false will solve the issue and eliminate the error.
FAQ
You can view latest topics and suggested topics that’ll help you as a new programmer.
– What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.
– What Is a Primary Expression in C Language?
A primary expression is the basic element of a complex expression. The identifiers, literals, constants, names, etc are considered primary expressions in the C programming language.
– What Are the Types of Expressions?
The different types of expressions include arithmetic, character, and logical or relational expressions. An arithmetic expression returns an arithmetic value. A character expression gives back a character value. Similarly, a logical value will be the output of a logical or relational expression.
Conclusion
The above error revolves around syntax mistakes and can be solved easily with a little code investigation. The noteworthy points depicting the solutions have been written below to help you out in removing the error:
- Never mention the data type of parameters while calling a function
- Ensure that you pass the correct type of arguments to the given function
- You should not miss a curly bracket or add an extra one
- The if statement should always be used with the expressions, expression results, true, or false
The more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.
Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.
We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.
Table of Contents
- How to fix “Expected Primary-Expression Before” error?
- Type 1: Expected primary-expression before ‘}’ token
- Type 2: Expected primary expression before ‘)’ token
- Type 3: Expected primary-expression before ‘enum’
- Type 4: Expected primary expression before ‘.’
- Type 5: Expected primary-expression before ‘word’
- Type 6: Expected primary-expression before ‘else’
- Conclusion
I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.
Type 1: Expected primary-expression before ‘}’ token
This error occurs when when the opening curly brackets ‘{‘ are not properly followed by the closing curly bracket ‘}’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.
Type 2: Expected primary expression before ‘)’ token
Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.
#include <Adafruit_NeoPixel.h>
#include <BlynkSimpleEsp8266.h>
#include <ESP8266WiFi.h>
#define PIN D1
#define NUMPIXELS 597
int red = 0;
int green = 0;
int blue = 0;
int game = 0;
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
Blynk.begin("d410a13b55560fbdfb3df5fe2a2ff5", "8", "12345670");
pixels.begin();
pixels.show();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
BLYNK_WRITE(V1) {
game = 1;
int R = param[0].asInt();
int G = param[1].asInt();
int B = param[2].asInt();
setSome(R, G, B);
}
BLYNK_WRITE(V2) {
if (param.asInt()==1) {
game = 2;
rainbow(uint8_t); // Rainbow
}
else {
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
Blynk.run();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i<NUMPIXELS; i++) {
pixels.setPixelColor(i, Wheel((i+j) & 255));
}
pixels.show();
delay(wait);
}
// delay(1);
}
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}BLYNK_WRITE(V3) {
if (param.asInt()) {
game = 3;
setAll(125, 47, 0); //candle
}
else {
}
}
BLYNK_WRITE(V4) {
game = 4;
int Bright = param.asInt();
pixels.setBrightness(Bright);
pixels.show();
}
BLYNK_WRITE(V5) {
if (param.asInt()) {
game = 5;
setAll(85, 0, 255);
}
else {
}
}
BLYNK_WRITE(V6) {
if (param.asInt()) {
game = 6;
oFF(red, green, blue);
// fullOff();
}
else {
}
}
BLYNK_WRITE(V7) {
if (param.asInt()) {
game = 7;
setAll(255, 0, 85);
}
else {
}
}
BLYNK_WRITE(V8) {
if (param.asInt()) {
game = 8;
setAll(90, 90, 90);
}
else {
}
}
BLYNK_WRITE(V9) {
if (param.asInt()) {
game = 9;
setAll(255, 130, 130);
}
else {
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void oFF(byte r, byte g, byte b) {
if (game == 1) {
offsome(r, g, b);
}
else if (game == 2) {
offall(r, g, b);
}
else if (game == 3) {
offall(r, g, b);
}
else if (game == 4) {
offall(r, g, b);
}
else if (game == 5) {
offall(r, g, b);
}
else if (game == 6) {
offall(r, g, b);
}
else if (game == 7) {
offall(r, g, b);
}
else if (game == 8) {
offall(r, g, b);
}
else if (game == 9) {
offall(r, g, b);
}
}
void offall(byte r, byte g, byte b) {
uint32_t x = r, y = g, z = b;
for (x; x > 0; x--) {
if( y > 0 )
y--;
if( z > 0 )
z--;
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
delay(0);
}
//delay(0);
}
void offsome(byte r, byte g, byte b) {
uint32_t x = r, y = g, z = b;
for (x; x > 0; x--) {
if( y > 0 )
y--;
if( z > 0 )
z--;
for(int i = 87; i < 214; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
for(int i = 385; i < 510; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
delay(0);
}
}
void setAll(byte r, byte g, byte b) {
uint16_t x = 0, y = 0, z = 0;
for (x; x < r; x++) {
if( y < g )
y++;
if( z < b )
z++;
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
red = r;
green = g;
blue = b;
delay(0);
}
//delay(0);
}
void setSome(byte r, byte g, byte b) {
uint16_t x = 0, y = 0, z = 0;
for (x; x < r; x++) {
if( y < g )
y++;
if( z < b )
z++;
for(int i = 86; i < 212; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
for(int i = 385; i < 512; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
red = r;
green = g;
blue = b;
delay(0);
}
//delay(0);
}
void fullOff() {
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0));
}
pixels.show();
}
Solution 1:
The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.
BLYNK_WRITE(V2) {
if (param.asInt()==1) {
game = 2;
rainbow(uint8_t); // Rainbow
}
else {
}
}
Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.
Type 3: Expected primary-expression before ‘enum’
Example 1: All credits to this thread.
#include <iostream>
using namespace std;
int main()
{
enum userchoice
{
Toyota = 1,
Lamborghini,
Ferrari,
Holden,
Range Rover
};
enum quizlevels
{
Hardquestions = 1,
Mediumquestions,
Easyquestions
};
return 0;
}
Solution 1:
The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:
#include <iostream>
using namespace std;
enum userchoice
{
Toyota = 1,
Lamborghini,
Ferrari,
Holden,
RangeRover
};
enum quizlevels
{
HardQuestions = 1,
MediumQuestions,
EasyQuestions
};
int main()
{
return 0;
}
Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.
Type 4: Expected primary expression before ‘.’
Example 1: All credits go to this thread.
#include <iostream>
using std::cout;
using std::endl;
class square {
public:
double length, width;
square(double length, double width);
square();
~square();
double perimeter();
};
double square::perimeter() {
return 2*square.length + 2*square.width;
}
int main() {
square sq(4.0, 4.0);
cout << sq.perimeter() << endl;
return 0;
}
Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.
#include <iostream>
using std::cout;
using std::endl;
class square {
public:
double length, width;
square(double length, double width);
square();
~square();
double perimeter();
};
double square::perimeter() {
return 2*length + 2*width;
}
int main() {
square sq(4.0, 4.0);
cout << sq.perimeter() << endl;
return 0;
}
Type 5: Expected primary-expression before ‘word’
Example 1: All credits go to this thread.
#include <iostream>
#include <string>
using namespace std;
string userInput();
int wordLengthFunction(string word);
int permutation(int wordLength);
int main()
{
string word = userInput();
int wordLength = wordLengthFunction(string word);
cout << word << " has " << permutation(wordLength) << " permutations." << endl;
return 0;
}
string userInput()
{
string word;
cout << "Please enter a word: ";
cin >> word;
return word;
}
int wordLengthFunction(string word)
{
int wordLength;
wordLength = word.length();
return wordLength;
}
int permutation(int wordLength)
{
if (wordLength == 1)
{
return wordLength;
}
else
{
return wordLength * permutation(wordLength - 1);
}
}
Solution 1:
Here, they are incorrectly using string inside wordLengthFunction().
Fixing it is simple, simply replace
int wordLength = wordLengthFunction(string word);
by
int wordLength = wordLengthFunction(word);
Type 6: Expected primary-expression before ‘else’
Example 1: All credit goes to this thread.
// Items for sale:
// Gizmos - Product number 0-999
// Widgets - Product number 1000-1999
// doohickeys - Product number 2000-2999
// thingamajigs - Product number 3000-3999
// Product number >3999 = Invalid Item
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
float ProdNumb; // Product Number
double PrG; // Product Number for Gizmo
double NG; // Number of items
double PG; // Price of Item
double PrW; // Product Number for Widgets
double NW; // Number of items
double PW; // Price of Item
double PrD; // Product Number for Doohickeys
double ND ; // Number of items
double PD ; // Price of Item
double PrT; // Product Number for Thingamajigs
double NT; // Number of items
double PT; // Price of Item
double PrI; //Product Number for Invalid (> 3999)
double NI; // Number of items
double PI; // Price of Item
double total = 0;
int main ()
{
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
while (ProdNumb != -1)
{
if (ProdNumb >= 0 && ProdNumb <= 999)
{
ProdNumb == PrG;
cout << "Enter the number of items sold: ";
cin >> NG;
cout << "Enter the price of one of the items sold: ";
cin >> PG;
}
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
else (ProdNumb >= 1000 && ProdNumb <= 1999)
{
ProdNumb == PrW;
cout << "Enter the number of items sold: ";
cin >> NW;
cout << "Enter the price of one of the items sold: ";
cin >> PW;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb >= 2000 && ProdNumb <= 2999)
{
ProdNumb == PrD;
cout << "Enter the number of items sold: ";
cin >> ND;
cout << "Enter the price of one of the items sold: ";
cin >> PD;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb >= 3000 && ProdNumb <= 3999)
{
ProdNumb == PrT;
cout << "Enter the number of items sold: ";
cin >> NT;
cout << "Enter the price of one of the items sold: ";
cin >> PT;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb <= -2 && ProdNumb == 0 && ProdNumb >= 4000)
{
ProdNumb == PrI;
cout << "Enter the number of items sold: ";
cin >> NI;
cout << "Enter the price of one of the items sold: ";
cin >> PI;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
}
cout << "***** Product Sales Summary *****";
cout << "n";
cout << "n";
cout << "Gizmo Count: ";
total += NG;
cout << NG;
cout << "n";
cout << "Gizmo Sales Total: ";
cout << (NG)*(PG);
cout << "n";
cout << "n";
cout << "Widget Count: ";
total += NW;
cout << NW;
cout << "n";
cout << "Widget Sales Total: ";
cout << (NW)*(PW);
cout << "n";
cout << "n";
cout << "Dookickey Count: ";
total += ND;
cout << ND;
cout << "n";
cout << "Doohickey Sales Total: ";
cout << (ND)*(PD);
cout << "n";
cout << "n";
cout << "Thingamajig Count: ";
total += NT;
cout << NT;
cout << "n";
cout << "Thingamajig Sales Total: ";
cout << (NT)*(PT);
cout << "n";
cout << "n";
cout << "Invalid Sales: ";
total += NI;
cout << NI;
return 0;
}
Solution 1:
This code is not correct because after the if statement is closed with ‘}’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘}’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.
Conclusion
And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.
Also, tell me which one of the 6 types were you experiencing in the comments below.
DmitryTheAdmin |
|
Статус: Новичок Группы: Участники
|
При попытке собрать библиотеку libphpcades получаю множество ошибок синтаксиса некоторых заголовочных файлов. Уже всю голову сломал и все равно понять не могу, почему так Моя конфигурация:
|
|
|
cross |
|
Статус: Сотрудник Группы: Администраторы, Участники Сказал(а) «Спасибо»: 3 раз |
У вас первая и вторая команда (eval и make) выполняются из разных окружений из-за sudo. Из-за этого переменные которые определились в eval не передаются в make. |
Техническую поддержку оказываем тут. |
|
|
|
Пользователи, просматривающие эту тему |
Guest |
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.