Error expected primary expression before long

What is the problem with my code ? prog.cpp: In function ‘void helper()’: prog.cpp:15:25: error: expected primary-expression before ‘long’ ans = ans + max(long long(0),vec[i]-i); #include <bit...

What is the problem with my code ?

prog.cpp: In function ‘void helper()’:
prog.cpp:15:25: error: expected primary-expression before ‘long’
ans = ans + max(long long(0),vec[i]-i);

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007

void helper(){
    ll n;
    cin>>n;
    vector<ll>vec(n);
    for(ll i=0;i<n;i++)
        cin>>vec[i];
    sort(vec.begin(),vec.end(),greater<ll>());
    ll ans=0;
    for(ll i=0;i<n;i++){
        ans = ans + max(long long(0),vec[i]-i);
        ans=ans % mod;
    }
    cout<<ans<<endl;
}

int main() {
    int test;cin>>test;
    while(test--){
        helper();
    }
    
    return 0;
}

Evg's user avatar

Evg

24.1k5 gold badges42 silver badges79 bronze badges

asked Feb 4, 2022 at 7:37

SUKRITI GUIN's user avatar

2

You can correct the error following one of these ways:
(ll)0 or (long long)0 or 0ll

answered Feb 4, 2022 at 8:13

Md. Faisal Habib's user avatar

2

The formal rule is that a constructor like type cast like long long(0) can only have a one word type name, and long long is two words. Oops, just doesn’t work.

Using a proper C++ type cast like static_cast<long long>(0) does work. However, for a constant you could just use 0LL and avoid the cast altogether.

answered Feb 4, 2022 at 10:20

BoP's user avatar

BoPBoP

1,8281 gold badge12 silver badges18 bronze badges

I know that a lot of people meet this error. I did do search work but it seems that this error msg appears in all different situations. Could you please tell me what’s wrong? Basically this class stores an int array of a long input. THis error is in the function num()

and another error:

main.cpp:43: error: invalid conversion from ‘num*’ to ‘long int’
main.cpp:43: error:   initializing argument 1 of ‘num::num(long int)’

#include <iostream>
#include <fstream>
using namespace std;
//ifstream fin;
//ofstream fout;
class num 
{
     public:
     int dig[9];
      void breakDown(long input)
     {   
             for(int digPos=0;input>0;digPos++)
             {   
                     dig[digPos]=input-((int)input/10)*10;
                     input=(int)input/10;
             }   
     }   
     num(long in) // constructor
     {   
             breakDown(long in);
     }   
     int outPut()
     {   
             for(int digPos=0;digPos<9;digPos++)
             {   
                     cout << dig[digPos];
             }   
             return 0;
     }    
};

//int init()
//{
//      fin.open("runround.in",ifstream::in);
//      fout.open("runround.out");
//}


int main()
{
//        init();
     num num1=new num((long)81236);
}

asked Nov 26, 2011 at 2:45

YankeeWhiskey's user avatar

YankeeWhiskeyYankeeWhiskey

1,5223 gold badges20 silver badges32 bronze badges

The error is here:

num(long in) // constructor
{   
    breakDown(long in);
}

change it to this:

num(long in) // constructor
{
    breakDown(in);
}

You don’t specify types when you call a function.


The other error is here:

num num1=new num((long)81236);

new num returns a pointer. But you are assigning it to a num object — which is incompatible.

You have two options here:

num num1((long)81236);

This will create a num object locally on the stack.

The other option is:

num *num1 = new num((long)81236);

This will allocate a num object on the heap. But you need to free it later with delete.

answered Nov 26, 2011 at 2:46

Mysticial's user avatar

MysticialMysticial

461k45 gold badges333 silver badges329 bronze badges

2

prutkin41

0 / 0 / 0

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

Сообщений: 4

1

20.07.2012, 07:23. Показов 32218. Ответов 7

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


код

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
#include <iostream.h>
using namespace std;
#include <windows.h>
 
int show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
}
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



25 / 25 / 5

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

Сообщений: 141

20.07.2012, 08:18

2

Функция how_big_and_litle не возвращает значение, а в заголовке она определена как возвращающая значение. Нужно либо в функцию return 0; поставить либо в определении функции вместо int поставить void



0



prutkin41

0 / 0 / 0

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

Сообщений: 4

20.07.2012, 08:29

 [ТС]

3

так не работает

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
int show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
   
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
  return(0);
}
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}



0



xADMIRALx

69 / 63 / 5

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

Сообщений: 291

20.07.2012, 09:10

4

Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы

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
#include <iostream>
#include <stdlib.h> // для system
 
 
using namespace std;
void show_big_and_litle(int a, int b, int c);
 
 
 
int main(void)
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
}    
void show_big_and_litle(int a, int b, int c)
{
  
  int small=a;
  int big=a;
   if(b>big)
    big=b;
   if(b<small)
    small=b;
   if(c>big)
    big=c;
   if(c<small)
    small=c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<small<<endl;
}



0



Infinity3000

1066 / 583 / 87

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

Сообщений: 1,255

20.07.2012, 09:52

5

Цитата
Сообщение от xADMIRALx
Посмотреть сообщение

Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы

прототип функции не обязательно обьявлять если функция реализованая до первого ее вызова!

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
#include <iostream.h>
using namespace std;
#include <windows.h>
 
void show_big_and_litle(int a, int b, int c)
{
  int smal = a;
  int big = a;
   if(b > big)
   {
    big = b;
   }
  if(b < smal)
    smal = b;
   if(c > big)
    big = c;
   if(c < smal)
    smal = c;
     
  cout<<"Самое  большое значение равно "<<big<<endl;
  cout<<"Самое маленькое значение равно "<<smal<<endl;
 
}
int main()
{
    show_big_and_litle(1,2,3);
    show_big_and_litle(500,0,-500);
    show_big_and_litle(1001,1001,1001);
  system("pause");
  return 0;
}



1



0 / 0 / 0

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

Сообщений: 4

20.07.2012, 12:20

 [ТС]

6

почему со «smal» компилируется, а с изначальным «small» -нет?



0



Schizorb

512 / 464 / 81

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

Сообщений: 869

Записей в блоге: 1

20.07.2012, 12:36

7

prutkin41, не подключай <windows.h>, в нем опеределена

C++
1
#define small char

Добавлено через 1 минуту
В этой задаче достаточно подключить:
#include <iostream>
#include <cstdlib>



1



0 / 0 / 0

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

Сообщений: 4

20.07.2012, 14:04

 [ТС]

8

почему возникает переполнение? извиняюсь за нубские вопросы — надо разобраться



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

20.07.2012, 14:04

Помогаю со студенческими работами здесь

Ошибка «expected primary-expression before ‘>’ token»
Задача: Задано линейный массив целых чисел. Увеличить на 2 каждый неотъемлемый элемент
массива….

Перегрузка оператора <<: «expected primary-expression»
Здравствуйте, можете пожалуйста подсказать в чём может быть ошибка. уже долго сижу и никак не могу…

Исправить ошибку «expected primary-expression»
Уважаемые форумчане помогите разобраться с простейшей арифметической программой:
#include…

expected primary-expression before «bre» ; expected `;’ before «bre» ; `bre’ undeclared (first use this function)
#include &lt;iostream&gt;
using namespace std;
struct point
{
int x;
int y;
};
int…

expected primary-expression before «else»
я написал эту прог чтобы он считывал слов в приложении.помогите исправит ошибки.если не трудно)…

В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно»
В зависимости от времени года &quot;весна&quot;, &quot;лето&quot;, &quot;осень&quot;, &quot;зима&quot; определить погоду &quot;тепло&quot;,…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

How to fix expected primary expression beforeThe 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

What is expected primary expression before errorThe 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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

“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.

I can’t figure out these errors. Every function call I make in the cpp file gives me these errors:


movie.cpp: In member function ‘void movie::menu(int, movie*)’:
movie.cpp:57: error: expected primary-expression before ‘*’ token
movie.cpp: In member function ‘void movie::enter_movie(movie*)’:
movie.cpp:68: error: expected primary-expression before ‘name’
movie.cpp:69: error: expected primary-expression before ‘int’
movie.cpp:70: error: expected primary-expression before ‘int’
movie.cpp:71: error: expected primary-expression before ‘*’ token
movie.cpp:72: error: expected primary-expression before ‘rating’
movie.cpp:73: error: expected primary-expression before ‘int’
main.cpp: In function ‘int main()’:
main.cpp:29: error: expected primary-expression before ‘int’
main.cpp:29: error: expected primary-expression before ‘*’ token
main.cpp:29: error: expected primary-expression before ‘)’ token

Lines 68-73 correspond to the enter_movie() function. line 29 is for main’s call to the menu function.

class

1
2
3
4
5
6
7
8
9
class movie
{
	private:
                // There's several private members here
	public:
		void menu( int, movie * );
		void enter_movie( movie * );
                // there's several other functions here, their calls can be seen below
};

cpp

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
void movie::menu( int choose, movie *m )
{
	do
	{	
		cout << "Would you like to enter or rent a movie?" << endl;
		cout << "( 1 - enter, 2 - rent, 0 - exit ): ";
		cin >> choose;
		cout << endl;
	}
	while ( choose >= 0 && choose <= 2 );

	if ( choose == 1 )
		m->enter_movie( movie *m ); //supposed to call enter movie function.
	if ( choose == 2 )
		// Enter search mode
	if ( choose == 0 )
		exit(1);
}

void movie::enter_movie( movie *m )
{
	m->set_name( string name );
	m->set_stars( int stars );
	m->set_num_cast( int num_cast );
	m->set_cast( string *cast );
	m->set_rating( string rating );
	m->set_copies( int copies );
        //these functions are the other public member functions, their parameters are the 
        //private member variables.
}

main

1
2
3
4
5
6
7
8
int main()
{
	netflix Netflix;
	movie Movie;
	Movie.menu( int, movie * );

	return 0;
}

I just want to get past these errors at the moment. Also movie * is from the movie class being a private member of another class. I’m guessing I shouldn’t be using it like this although I was told today that I should. I don’t know, I barely know what I’m doing. But if I could get some assistance with these errors I’ll be eternally grateful. :)

Could you indicate what lines on the errors correspond to what lines in your posted code?

oops must have forgotten:
movie.cpp line 57 = cpp line 13
movie.cpp lines 68-73 = lines 22-27
main.cpp line 29 = main line 5

thanks for checking it out :)

Do you know how to call a function? It sounds simple, but it seems the errors are all from the same kind of mistake when calling the function. You might want to read this tutorial, paying close attention to how functions are called in the examples:
http://www.cplusplus.com/doc/tutorial/functions/

Sadly I’ve been reading about functions all day trying to figure out what it is that I’m doing wrong. I read through the tutorial page to just to look for any thing I may have missed. Still I’m finding very little info on properly calling member functions of classes with private variables. That wasn’t covered in the tutorial, or hardly any where that I can find. I tried using the dot (.) instead of the arrow (->) but that made my errors worse.
The way I have them set up now was suggested by a TA. So I don’t really know what else to do, every one I’ve talked to so far has lead me to the code I have but no one’s been able to get past these errors. I’ve been assuming that there’s something horribly wrong with the function call but I just can’t find it.

Your use of . and -> are fine; it is the parameter list that is the issue. Compare that to the tutorial’s example of calling a function and see if you can spot the difference.

So all the examples have parameters that are empty, with variables, with types, or with types and variables. Some use the &. I swear I’ve tried all possible combinations. Unless there’s somehow one Ive missed I honestly don’t see anything different. Also all the examples have quite different parameter set-ups, could you please point out one of the examples that has the difference in it and maybe I could better pinpoint what difference I’m looking for. Thank you. :)

movie.h
lines 6-7: You don’t need to pass a pointer to movie as an argument. A function that is a member of a class implicity has access to the member variables of the class.

movie.cpp
Line 1,20: Ditto.

Line 13: Simply call enter_movie(). You don’t need to pass any arguments.

Lines 22-27: 1) You don’t need the m-> to call member functions of your class. 2) You don’t specify types in a function call. Types are only specified in a functin prototype. 3) Since you haven’t shown these functions, it’s not clear if these functions are prompting for input. If they are, you don’t need arguments at all.

main.cpp
line 5: 1) You have to pass an integer value, not a type. Again, you don’t specify types in a function call. 2) movie * is a type. You don’t need this argument since the instance of movie is specified by the Movie variable.

You are confusing two concepts:

1. Declaring and defining functions and members of classes.

2. Calling functions and members of classes ( whether you call a class member on an object or a static member on a class)

When you define a function, you have to add the type of the parameter:

1
2
3
int sum( int number1, int number2) {
    return number1 + number2;
}

Now I want to use the function I wrote:

1
2
3
4
5

int main(void) {
    std::cout << sum( 1, 2) << std::endl;
}

What you do wrong in the main function:

1
2
3
4
5
6
7
8
int main()
{
	netflix Netflix;
	movie Movie;
	Movie.menu( int, movie * );

	return 0;
}

Is calling the member function with types, instead of values or variables. Try this:

1
2
3
4
5
6
7
8
9
int main()
{
	netflix Netflix;
	movie Movie;
        movie *pointerToMovieObject = new movie();
	Movie.menu( 3, pointerToMovieObject );

	return 0;
}

Post the entire code when you’re done.
I will help you out with your code

Alrighty, it took a mix of both you guys advice but I’m down to just one error:


movie.cpp:42: error: variable or field ‘menu’ declared void

42 in my code is line 1 above.

I took out the pointers and the m->. I took out the parameters of all the function calls with two exceptions. Main line 5 and movie.cpp line 1 have a 0 in them and that’s it. Also in movie.cpp line 20 it’s now just void movie::enter_movie( movie ). It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors. I tried just declaring the function in the class without any parameters at all since I was asking for the number inside the function but it got mad at me for that too. Feels like c++ is just out to get me. I do things that seem logical to me but the compiler blows up overtime I try something. Anyways, any clues on that last error? :)

Last edited on

@mt106250
Hi didn’t see your post there till just now, I’ll post it here in a bit. I’ll warn you it’s long, but thank you for helping:)

@andres81

There are a few problems with the code you posted:
main.cpp
Line 5: There is no reason to dynamically allocate an instance of movie.
Line 6: As I pointed out before, there is no reason to pass a pointer to a movie instance assuming all the OP wants to do is update a single instance (Movie).
Line 7: You have a memory leak. The instance of movie that was dynamically allocated was never released.

@OP

It wouldn’t let me take it out or it got mad at me. I don’t really know why I need the number in the two function calls to get rid of so many errors.

In movie.cpp line 1, you’re passing choose as an argument. There is really no need for choose to be an argument since you prompt for it at line 7. However, if you remove choose as an argument, you must declare it locally within menu().

Last edited on

Ok here’s the whole thing, maybe that will clear any confusion of what I’ve attempted to do. Also there’s several blank functions that I just haven’t even gotten to yet because I either don’t know what I’m supposed to use it for or I’m waiting to get past these errors before I get into them. Figured I’d get past the current errors before I start making more. :)

net header

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
#ifndef NETFLIX_H
#define NETFLIX_H
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include "./movie.h"


class netflix
{

	private:
		movie *m;
		int num_movies;

	public:
		netflix();
		netflix( const netflix & );
		~netflix();
		void set_movie( movie * );
		void set_num_movies( int );
		movie get_movie();
		int get_num_movies();

};

#endif 

net.cpp

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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "./netflix.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;

netflix::netflix()
{

	m = NULL;
	num_movies = 0;

}

netflix::~netflix()
{

	delete [] m;
	m = NULL;

}

netflix::netflix( const netflix & ){}

void netflix::set_num_movies( int ){}

movie netflix::get_movie() { return *m; }
int netflix::get_num_movies() { return num_movies; }

movie header

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
#ifndef MOVIE_H
#define MOVIE_H
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>

using std::string;

class movie
{

	private:
		string name;
		int stars;
		int num_cast;
		string *cast;
		string rating;
		int copies;

	public:
		movie();
		~movie();
		movie( const movie & );
		void menu( int );
		void enter_movie( movie );
		void set_name( string );
		void set_stars( int );
		void set_num_cast( int );
		void set_cast( string * );
		void set_rating( string );
		void set_copies( int );
		string get_name();
		int get_stars();
		int get_num_cast();
		string get_cast();
		string get_rating();
		int get_copies();

};

#endif 

movie.cpp

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
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include "./movie.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;

movie::movie()
{

	stars = 0;
	num_cast = 0;
	cast = NULL;
	copies = 0;

}

movie::~movie()
{

	delete [] cast;
	cast = NULL;

}

movie::movie( const movie & ){}

void movie::menu( 0 )
{

	int choose;

	do
	{
	
		cout << "Would you like to enter or rent a movie?" << endl;
		cout << "( 1 - enter, 2 - rent, 3 - exit ): ";
		cin >> choose;
		cout << endl;
	
	}
	while ( choose >= 1 && choose <= 3 );

	if ( choose == 1 )
		enter_movie();
	if ( choose == 2 )
		// Enter search mode
	if ( choose == 3 )
		exit(1);

}

void movie::enter_movie( movie )
{

	set_name();
	set_stars();
	set_num_cast();
	set_cast();
	set_rating();
	set_copies();

}

void movie::set_name( string )
{

	cout << "Movie title: ";
	getline( cin, name );

}

void movie::set_stars( int )
{

	cout << "Number of stars: ";
	cin >> stars;

}

void movie::set_num_cast( int )
{

	cout << "Number of cast members: ";
	cin >> num_cast;

}

void movie::set_cast( string * )
{

	for ( int i = 0; i < num_cast; ++i )
	{
	
		cout << "Cast member #" << i << ": ";
		getline( cin, *cast );
	
	}

}

void movie::set_rating( string )
{

	cout << "Rating: ";
	getline( cin, rating );

}

void movie::set_copies( int )
{

	cout << "Number of copies: ";
	cin >> copies;

}

string movie::get_name() { return name; }
int movie::get_stars() { return stars; }
int movie::get_num_cast() { return num_cast; }
string movie::get_cast() { return *cast; }
string movie::get_rating() { return rating; }
int movie::get_copies() { return copies; }

main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include "./netflix.h"
#include "./movie.h"

using namespace std;

//void menu();

int main()
{

//	menu( int );

	netflix Netflix;
	movie Movie;
	movie *m = new movie();
	Movie.menu( 0 );

	return 0;

}

output: refers to line 32 in this post.


movie.cpp:42: error: variable or field ‘menu’ declared void

I’m sorry if the things I’ve done in this code are just ridiculous. I’m amazingly terrible at coding despite spending all of my free time reading the 2 books I have and going to TA office hours. I took me a week just to figure out how to begin designing the thing and it’s been a week of me being stuck at this point. Seems like every thing I do make it worse. I am dying to understand this stuff so any thing you can say to help will be greatly appreciated. Thank you much. :)

movie.cpp line 32: get rid of the 0. This function should not have any arguments. 0 is not valid in an argument list.

main.cpp line 19: get rid of this line. There is no reason to dynamically allocate a move instance. It’s also causing a memory leak since you never delete it.

main.cpp line 20: get rid of the 0. You can’t pass a 0 to a function that doesn’t take any arguments.

movie.cpp line 30: If you’re going to pass an argument here, you need to name the argument.

Line 57, 69, 77, 85, 93, 106, 114: Again, if you’re going to pass and argument to these functions, you need to specify a name, not just a type. You can get away with not specifying a name in the declaration, but a name is required in the definition. However, I don’t see that you need any of these arguments.

movie.h line 17: Why is cast a pointer? In movie.cpp line 100, you’re trying to do a getline to a null pointer. That’s going to cause a trap or an exception.

I’m assuming your intention here is to allow multiple cast members. If that’s what you’re trying to do, you should use a vector:

1
2
3
4
5
6
    vector<string>  cast;
...
// In movie::set_cast
   string cast_member;
   getline (cin, cast_member);
   cast.push_back (cast_member);

Likewise in netflix.h, I assume your intent with the movie pointer is to allow multiple movies. Again you should use a vector.

1
2
3
4
  vector<movie>  movies;
...
  // In netflix::set_movie you should be passing movie by reference
  movies.push_back (movie);

Last edited on

hmm, I made all the recommended changes. These are my new errors:


In file included from ./netflix.h:18,
                 from netflix.cpp:15:
././movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
././movie.h:28: error: expected ‘;’ before ‘<’ token
In file included from netflix.cpp:15:
./netflix.h:25: error: ISO C++ forbids declaration of ‘vector’ with no type
./netflix.h:25: error: expected ‘;’ before ‘<’ token
netflix.cpp: In constructor ‘netflix::netflix()’:
netflix.cpp:25: error: ‘m’ was not declared in this scope
netflix.cpp: In destructor ‘netflix::~netflix()’:
netflix.cpp:33: error: ‘m’ was not declared in this scope
netflix.cpp: At global scope:
netflix.cpp:40: error: prototype for ‘void netflix::set_movie()’ does not match any in class ‘netflix’
./netflix.h:33: error: candidate is: void netflix::set_movie(movie*)
netflix.cpp: In member function ‘movie netflix::get_movie()’:
netflix.cpp:44: error: ‘m’ was not declared in this scope
In file included from movie.cpp:15:
./movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
./movie.h:28: error: expected ‘;’ before ‘<’ token
movie.cpp: In constructor ‘movie::movie()’:
movie.cpp:27: error: ‘cast’ was not declared in this scope
movie.cpp: In destructor ‘movie::~movie()’:
movie.cpp:35: error: ‘cast’ was not declared in this scope
movie.cpp: At global scope:
movie.cpp:42: error: prototype for ‘void movie::menu()’ does not match any in class ‘movie’
./movie.h:37: error: candidate is: void movie::menu(int)
movie.cpp:67: error: prototype for ‘void movie::enter_movie()’ does not match any in class ‘movie’
./movie.h:38: error: candidate is: void movie::enter_movie(movie)
movie.cpp:79: error: prototype for ‘void movie::set_name()’ does not match any in class ‘movie’
./movie.h:39: error: candidate is: void movie::set_name(std::string)
movie.cpp:87: error: prototype for ‘void movie::set_stars()’ does not match any in class ‘movie’
./movie.h:40: error: candidate is: void movie::set_stars(int)
movie.cpp:95: error: prototype for ‘void movie::set_num_cast()’ does not match any in class ‘movie’
./movie.h:41: error: candidate is: void movie::set_num_cast(int)
movie.cpp:103: error: prototype for ‘void movie::set_cast()’ does not match any in class ‘movie’
./movie.h:42: error: candidate is: void movie::set_cast(std::string*)
movie.cpp:119: error: prototype for ‘void movie::set_rating()’ does not match any in class ‘movie’
./movie.h:43: error: candidate is: void movie::set_rating(std::string)
movie.cpp:127: error: prototype for ‘void movie::set_copies()’ does not match any in class ‘movie’
./movie.h:44: error: candidate is: void movie::set_copies(int)
movie.cpp: In member function ‘std::string movie::get_cast()’:
movie.cpp:138: error: ‘cast’ was not declared in this scope
In file included from ./netflix.h:18,
                 from main.cpp:15:
././movie.h:28: error: ISO C++ forbids declaration of ‘vector’ with no type
././movie.h:28: error: expected ‘;’ before ‘<’ token
In file included from main.cpp:15:
./netflix.h:25: error: ISO C++ forbids declaration of ‘vector’ with no type
./netflix.h:25: error: expected ‘;’ before ‘<’ token
main.cpp: In function ‘int main()’:
main.cpp:29: error: no matching function for call to ‘movie::menu()’
././movie.h:37: note: candidates are: void movie::menu(int)

There’s a lot of errors in here that I previously had, but now theres even more. :(
I was sure to add the #include <vector> . Other than that, not sure.

Why dont you place your netflix header and movie header together?
Along with netflix.cpp and movie.cpp

That’s actually how I had it originally, but it’s required that everything be separate. It’s dumb, I hate it, don’t understand why it has to be this way. I would totally prefer to just have everything in one file. As it is I have to have 5 terminal windows open at once so I can see everything. It really bums me out. :)

That’s understandable.

I think what you should do is work on your other functions, that way you can fix all your errors

If your entire program compiles, post your program so we adjust things more!

  1. В общем, в ардуино я полный профан, при компиляции кода выдает такую ошибку:
    Arduino: 1.8.7 (Windows 10), Плата:»Arduino Uno»

    exit status 1
    expected primary-expression before ‘{‘ token
    Не ругайтесь сильно, я тупой)
    Код:

    #define PIN_TRIG 12
    #define PIN_ECHO 11
    int piezoPin = 3;
    long duration, cm;
    void setup() {
      // Инициализируем взаимодействие по последовательному порту
      Serial.begin (9600);
      //Определяем вводы и выводы
      pinMode(PIN_TRIG, OUTPUT);
      pinMode(PIN_ECHO, INPUT);
    }
    void loop() {
      // Сначала генерируем короткий импульс длительностью 2-5 микросекунд.
      digitalWrite(PIN_TRIG, LOW);
      delayMicroseconds(5);
      digitalWrite(PIN_TRIG, HIGH);
      // Выставив высокий уровень сигнала, ждем около 10 микросекунд. В этот момент датчик будет посылать сигналы с частотой 40 КГц.
      delayMicroseconds(10);
      digitalWrite(PIN_TRIG, LOW);
      //  Время задержки акустического сигнала на эхолокаторе.
      duration = pulseIn(PIN_ECHO, HIGH);
      // Теперь осталось преобразовать время в расстояние
      cm = (duration / 2) / 29.1;
      Serial.print(«Расстояние до объекта: «);
      Serial.print(cm);
      Serial.println(» см.»);
      // Задержка между измерениями для корректной работы скеча
      delay(250);
      if
      {
        cm<160
      }
      else
      {
       tone(piezoPin, 2000); // Запустили звучание
      delay(500);
      noTone(); // Остановили звучание
      }

     

    }

  2. В сообщении об ошибке должно быть еще номер строчки и позиция в строке. А то куда смотреть ?
    if — если — если что ? Здесь не дописано !!! Зайдите в справочник Ардуино насчет «if».
    После if должна стоять круглая скобка, а не «с хвостиком».

    Последнее редактирование: 29 янв 2020

  3. ошибка(и) здесь delay(250);
    if
    {
    cm<160
    }
    else
    {
    tone(pie

  4. Вот тупо скопированное сообщение:
    Arduino: 1.8.7 (Windows 10), Плата:»Arduino Uno»

    C:UsersТРРХАЧАDocumentsArduino________________.ino: In function ‘void loop()’:

    ________:30:2: error: expected primary-expression before ‘{‘ token

    ________:30:2: error: expected ‘)’ before ‘{‘ token

    ________:41:1: error: expected primary-expression before ‘}’ token

    exit status 1
    expected primary-expression before ‘{‘ token

    Этот отчёт будет иметь больше информации с
    включенной опцией Файл -> Настройки ->
    «Показать подробный вывод во время компиляции»

  5. if (cm < 160 )
    {
    tone(piezoPin, 2000); // Запустили звучание
      delay(500);
      noTone(); // Остановили звучание
    }
    else
    {
    tone(piezoPin, 200); // Запустили звучание
      delay(500);
      noTone(); // Остановили звучание
    }

    Должно быть в примерно таком виде.

  6. Ставьте нормальную IDE с подсветкой синтаксиса, а не этот блокнот. Тем более на стадии, когда

  7. оххх, а может и с на русском есть? Дашь ссылку?

  8. Все равно ошибка:
    Arduino: 1.8.7 (Windows 10), Плата:»Arduino Uno»

    C:UsersТРРХАЧАDocumentsArduino________________.ino: In function ‘void loop()’:

    ________:33:10: error: too few arguments to function ‘void noTone(uint8_t)’

    In file included from sketch________.ino.cpp:1:0:

    C:UsersТРР ХАЧАAppDataLocalArduino15packagesarduinohardwareavr1.8.2coresarduino/Arduino.h:248:6: note: declared here

    void noTone(uint8_t _pin);

    ^~~~~~

    ________:39:10: error: too few arguments to function ‘void noTone(uint8_t)’

    In file included from sketch________.ino.cpp:1:0:

    C:UsersТРР ХАЧАAppDataLocalArduino15packagesarduinohardwareavr1.8.2coresarduino/Arduino.h:248:6: note: declared here

    void noTone(uint8_t _pin);

    ^~~~~~

    exit status 1
    too few arguments to function ‘void noTone(uint8_t)’

    Этот отчёт будет иметь больше информации с
    включенной опцией Файл -> Настройки ->
    «Показать подробный вывод во время компиляции»

  9. Atmel Studio с сайта микрочипа, а потом оттуда ставишь нахлобучку для ардуины. И там же можешь поставить любую цветовую тему с любой подсветкой. Потом в блокнот уже не вернёшься. Никогда.

  10. А не перевести самостоятельно? Перевод:

    и ниже подсказка:

  11. Проблюешься, и поставишь Notepad ++, Sublime, Atom, etc.

    Навсегда.

  12. noTone(piezoPin);

    Notepad++Portable

  13. Студия требовательна к пк, хоть и решает множество задач. Да и аглицкий там, под тз тс не проходит)

  14. Последнее редактирование: 29 янв 2020

  15. А мне нравится VSCode. Работает на любом навозе. Прикрутить можно к любому дереву. Но мне, увы, мозгов на это не хватает. Поэтому пока прикручен к IAR)У меня Atmel Studio на ноуте запускается минуты за полторы (ОЗУ 8ГБ, но тухлый проц). Но потом нормально работает. А вот CCS и Simplicity Studio — они на эклипсе. Вот это вообще вилы. Даже если и загрузятся, то потом ещё и тупят((( Приходится большого брата звать на помощь

  16. Блокнотом++ пользуюсь в любой момент когда нужно что-то записать.
    Со студией аналогично все. В другое не лезу)

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

Понравилась статья? Поделить с друзьями:
  • Error expected primary expression before const
  • Error expect received toequal expected deep equality
  • Error expected primary expression before char
  • Error exp was not declared in this scope
  • Error exiting jvm with code 1 org apache zookeeper util serviceutils