Error expected primary expression before token arduino

When i attempt to compile the code HERE I get the error "expected primary-expression before ')' token" and it highlights this line: sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);

When i attempt to compile the code HERE
I get the error «expected primary-expression before ‘)’ token» and it highlights this line:

  sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);

asked Dec 8, 2013 at 17:54

joeybab3's user avatar

joeybab3joeybab3

2932 gold badges7 silver badges23 bronze badges

2

So that this does not still come up in «unanswered», I’ll answer it… As wildplasser said, i forgot to define the #define TEMPERATURE_PRECISION line…

answered Dec 13, 2013 at 4:35

joeybab3's user avatar

joeybab3joeybab3

2932 gold badges7 silver badges23 bronze badges

#include "Ultrasonic.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  // put your setup code here, to run once:
  lcd.begin();
  Serial.begin(9600);
}
Ultrasonic ultrasonic(11, 12); //Ultrasonic ultrasonic(Trig,Echo);
void loop()
{
  int a = (Ultrasonic.Ranging(CM));
  if (a >= 15 && a < 20)
  { Serial.println("guvenli");
    lcd.print("guvenli");
    delay(500);
    lcd.clear();
    tone(3, 2000, 100);
    delay(500);
    noTone(3);
  }
  if (a >= 10 && a < 15) {
    Serial.println("guvenli dikkat");
    lcd.print("guvenli dikkat");
    delay(500);
    lcd.clear();
    tone(3, 2000, 50);
    delay(250);
    noTone(3);
  }
  if (a < 5)
  {
    Serial.println("vurdun");
    lcd.print("vurdun");
    delay(500);
    lcd.clear();**uıhhf
    tone(3, 2000, 50);
    delay(50);
    noTone(3);
  }
}

In this code i’m getting an error like this:

   C:Users*AppDataLocalTemparduino_modified_sketch_113625sketch_apr29a.ino: In function 'void loop()':

sketch_apr29a:19:22: error: expected primary-expression before '.' token

   int a = (Ultrasonic.Ranging(CM)); 

                      ^

exit status 1
expected primary-expression before '.' token

  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. Они просто не в курсе, что так можно! Там же не только подсветка, но и автопоиск, подсказки, рефакторинг и прочее, прочее, без чего в принципе невозможно осваивать новые горизонты!

Содержание

  1. Arduino.ru
  2. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  3. forum.arduino.ru
  4. Прошу помощи
  5. Fix “Expected Primary-Expression Before” in C++ or Arduino
  6. How to fix “Expected Primary-Expression Before” error?
  7. Type 1: Expected primary-expression before ‘>’ token
  8. Type 2: Expected primary expression before ‘)’ token
  9. Type 3: Expected primary-expression before ‘enum’
  10. Type 4: Expected primary expression before ‘.’
  11. Type 5: Expected primary-expression before ‘word’
  12. Type 6: Expected primary-expression before ‘else’
  13. Conclusion

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

Прошу помощи

Приветствую. Проблема в следуещем, есть у меня друг который смог с ардуино вывести показания буста на штатный экран бк. Я от этой темы далек, он мне сказал купить платку нано, и дал чем прошить ее. сейчас связи с ним нет, а прошить не получается, выдает ошибку. Помогите с таким траблом мне .

опубликуйте весь код

покажите ошибку которую компилятор выдал

опубликуйте весь код

покажите ошибку которую компилятор выдал

Ошибку просто выделяешь мышкой в Arduino IDE и копируешь/вставляешь сюда текстом.

Ошибку просто выделяешь мышкой в Arduino IDE и копируешь/вставляешь сюда текстом.

rgdaudi, компилятор же Вам все написал.

Вот расскажите, что Вы хотели сказать в строках 67 и 68?

rgdaudi, компилятор же Вам все написал.

Вот расскажите, что Вы хотели сказать в строках 67 и 68?

[/quote]
Я ж и обратился за помощью сюда, если бы я что то понимал вопросов бы не возникло

Вопрос остается: что Вы хотели сказать строками 67 и 68?

Вопрос остается: что Вы хотели сказать строками 67 и 68?

Вопрос остается: что Вы хотели сказать строками 67 и 68?

Ладно, я даже готов согласиться, что не программа считывает значение в переменную, а сама переменная считывает значение сама в себя, но почему она это делает, пренебрегая правилами языка?

Ладно, я даже готов согласиться, что не программа считывает значение в переменную, а сама переменная считывает значение сама в себя, но почему она это делает, пренебрегая правилами языка?

[/quote] Да далек я ото всего этого, кто бы мне помог сейчас не на связи, вот и обратился я к Вам

Ну, у Вас есть два варианта:

1. «Подойти поближе» — т.е. ознакомиться с языком и принципами программирования.

2. Обратиться в раздел «Ищу исполнителя». Там Вам помогут за соответствующее вознаграждение.

Здесь Вам могут помочь осуществить п.1 т.е. освоить программирование, но делать за Вас работу, которая никому кроме Вас не интересна, никто не будет.

Пока могу еще раз посоветовать прочитать и понять выдаваемую компилятором диагностику. На строку 69 не обращайте внимания, это наведенка от предыдущей строки, а вот в строке 70 все достатояно четко сформулировано: Вы пытаетесь использовать нигде не описанную переменную.

Ну, у Вас есть два варианта:

1. «Подойти поближе» — т.е. ознакомиться с языком и принципами программирования.

2. Обратиться в раздел «Ищу исполнителя». Там Вам помогут за соответствующее вознаграждение.

Здесь Вам могут помочь осуществить п.1 т.е. освоить программирование, но делать за Вас работу, которая никому кроме Вас не интересна, никто не будет.

Пока могу еще раз посоветовать прочитать и понять выдаваемую компилятором диагностику. На строку 69 не обращайте внимания, это наведенка от предыдущей строки, а вот в строке 70 все достатояно четко сформулировано: Вы пытаетесь использовать нигде не описанную переменную.

Спасибо огромное идем по пункту 1) я нашел в чем проблема была

Источник

Fix “Expected Primary-Expression Before” in C++ or Arduino

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

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.

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.

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.

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:

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.

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.

Type 5: Expected primary-expression before ‘word’

Example 1: All credits go to this thread.

Solution 1:

Here, they are incorrectly using string inside wordLengthFunction().

Fixing it is simple, simply replace

Type 6: Expected primary-expression before ‘else’

Example 1: All credit goes to this thread.

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.

Источник

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

PlatformIO Community

Loading

Понравилась статья? Поделить с друзьями:
  • Error expected asm or attribute before token
  • Error expected primary expression before long
  • Error expected after class definition
  • Error expected primary expression before int
  • Error expected primary expression before float