Error expected while before token

I’m getting this error on the below code and can’t seem to see where i’m going wrong. Please could someone point me in the right direction. Thanks in advance.

**************The Error is ************************
*******In function ‘float calcActualAmount(float,int)’
Line62*expected ‘while’ before ‘(‘ token

The piece of code i’m getting the error on is:
************************************************

amountP = calcAllowedPerChild(nrChildrenP) — leftToSpend;

while (leftToSpend == 0);

}

return(amountP);
}

int main()

********************************************
#include <iostream>
using namespace std;

const float maxPerUnit = 20000.00;
//minPerChild includes a standard gift consisting of a bath towel and a facecloth
const float minPerChild = 100.00;
const float maxPerChild = 180.00;
//depending on the amount, the child may also get one or more of the following;
const float TOOTHBRUSH = 29.95;
const float HIGHLIGHTERS = 25.95;
const float CRAYONS = 17.95;
const float NOTEBOOK = 12.95;
const float PEN = 9.99;

float calcAllowedPerChild(int nrChildrenP)
{
float amtGiftP = 20000.00 / nrChildrenP;
return amtGiftP;
}

float calcActualAmount(float amountP, int nrChildrenP)
{
float leftToSpend;
if (calcAllowedPerChild(nrChildrenP) > 180)
amountP = 180;
else if (calcAllowedPerChild(nrChildrenP) < 180)
leftToSpend = calcAllowedPerChild(nrChildrenP) — 100;
do
{
for (int i = 1; i <= 5; i++)

switch (i)
{
case 1: leftToSpend -= TOOTHBRUSH;
break;

case 2: leftToSpend -= HIGHLIGHTERS;
break;

case 3: leftToSpend -= CRAYONS;
break;

case 4: leftToSpend -= NOTEBOOK;
break;

case 5: leftToSpend -= PEN;
break;
}

amountP = calcAllowedPerChild(nrChildrenP) — leftToSpend;

while (leftToSpend == 0);

}

return(amountP);
}

int main()
{
float amtGift; // Allowed amount per child
float amtSpentPerChild = 0.00; // actual amount spent per child
float totalSpent = 0.00; // total spent for 1 orphanage
float totalAll = 0.00; // total spent for all 4 orphanages
int nrChildren;

cout << «Enter the amount of children: » << endl;
cin >> nrChildren;
amtGift = calcAllowedPerChild(nrChildren);
cout.setf(ios::fixed);
cout.precision(2);
cout << endl << » Allowable amount per child : R» << amtGift;
cout << endl << endl;
amtSpentPerChild = calcActualAmount(amtGift, nrChildren);
cout << endl << » Actual amount spent per child : R» ;
cout << amtSpentPerChild << endl << endl;
totalSpent = calcTotalSpent(nrChildren, amtSpentPerChild);
cout << endl << » The actual amount spent was : R» ;
cout << totalSpent << endl;

system(«pause»);

return 0;

}

Last edited on

Use [code][/code] tags next time.

Your problem is that you need a ‘}’ before your while there. Go look at the syntax for a do…while loop again and you should see it.

Home »
C programs »
C common errors programs

Here, we will learn why an error: expected ‘)’ before ‘;’ token occurs and how to fix it in C programming language?

Submitted by IncludeHelp, on September 04, 2018

The error: expected ‘)’ before ‘;’ token may occur by terminating the statements which should not be terminated by the semicolon.

Consider the given example, here I terminated the #define statement by the semicolon, which should not be terminated.

Example:

#include <stdio.h>

#define MAX 10;

int main(void) {
	printf("MAX = %dn", MAX);
	return 0;
}

Output

prog.c: In function 'main':
prog.c:3:15: error: expected ')' before ';' token
 #define MAX 10;
               ^
prog.c:6:23: note: in expansion of macro 'MAX'
  printf("MAX = %dn", MAX);
                       ^~~

How to fix?

To fix this error, check the statement which should not be terminated and remove semicolons. To fix this error in this program, remove semicolon after the #define statement.

Correct code:

#include <stdio.h>

#define MAX 10

int main(void) {
	printf("MAX = %dn", MAX);
	return 0;
}

Output

MAX = 10

C Common Errors Programs »


  1. Здравствуйте.
    Помогите, пожалуйста, разобраться.

    С видео напечатал код в IDE. Выдаёт ошибку expected ‘)’ before ‘;’ token

    Причём, две одинаковых строчки, но с разницей только, что одна про минуты, а вторая про секунды, но как их не меняй местами, всегда ругается именно на ту, что с секундами:

    int seconds = numberOfSeconds(timeRemaining);

    Полный текст ошибки:

    C:Arduino2 minsketch_may05asketch_may05a.ino: In function ‘void countdown()’:

    sketch_may05a:30:49: error: expected ‘)’ before ‘;’ token

         int seconds = numberOfSeconds(timeRemaining);

                                                     ^

    exit status 1
    expected ‘)’ before ‘;’ token

    Вот этот кусок кода в видео:

    [​IMG]

    А вот этот же кусок кода после компиляции у меня:

    [​IMG]

    Если поменять порядок на

        int minutes = numberOfMinutes(timeRemaining);
        int seconds = numberOfSeconds(timeRemaining);  
     

    то он откомпилирует строчку с минутами и будет ругаться на вторую строчку с секундами.

    Код целиком:

    #define numberOfSeconds(_time_) ((_time_ / 1000%60)
    #define numberOfMinutes(_time_) (((_time_ / 1000) / 60) % 60)

    #include <TM1637Display.h>

    const uint8_t OFF[] = {0, 0, 0, 0};
    const uint8_t PLAY[] = {B01110011, B00111000, B01011111, B01101110};

    TM1637Display display(2, 3); // Clock pin, Data pin

    unsigned long timeLimit = 3600000;

    void setup() {
      Serial.begin(9600);
      //set brightness
      display.setBrightness(0x0c);
      //clear the display
      display.setSegments(OFF);

    }

    void countdown() {

      unsigned long timeRemaining = timeLimit millis();

      while (timeRemaining > 0) {

     
        int seconds = numberOfSeconds(timeRemaining);
        int minutes = numberOfMinutes(timeRemaining);

        display.showNumberDecEx(seconds, 0, true, 2, 2);
        display.showNumberDecEx(minutes, 0x80 >> 3, true, 2, 0);

        timeRemaining = timeLimit millis();

      }
    }

    void loop() {
      countdown();

    }

    Последнее редактирование: 5 май 2020

  2. В первой строке в коде пропущена скобка. Нужно так:

    #define numberOfSeconds(_time_) ((_time_ / 1000%60))
  3. Это помогло. Очень благодарен!)) Спасибо.

zhundik

0 / 0 / 1

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

Сообщений: 61

1

16.10.2014, 20:23. Показов 29048. Ответов 8

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


Ребят, подскажите(( Изучал Страуструпа, но застрял .. Теперь взял Дейтелов , пока вроде ничего )) Но только вот уже на втором проекте выскочила какая-то беда, и никак не пойму в чем подвох((
Это элемент-функции.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "invoice.h"
#include <iostream>
using namespace std;
 
 
void Invoice::setArt(string a)
{
    art=a;
}
void Invoice::setInfo(string b)
{
    info=b;
}
void Invoice::setX(int y)
{
    x=y;
}
void Invoice::setC(int z)
{
    c=z;
}
string Invoice::getArt()
{
    return art;
}
string Invoice::getInfo()
{
    return info;
}
int Invoice::getX()
{
    return x;
}
int Invoice::getC()
{
    return c;
}
int Invoice::getInvoiceAmount()
{
    return x*c;
}
Invoice::Invoice(string a; string b; int x; int c)
{
    setArt(a);
    setInfo(b);
    if(x<0) x=0;
    setX(x);
    setC(c);
}

Это сам класс

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
#ifndef INVOICE_H_INCLUDED
#define INVOICE_H_INCLUDED
#include <string>
#include <iostream>
using namespace std;
class Invoice
{
public:
    Invoice( int, int);
 
    void setArt(string);
    void setInfo(string);
    void setX (int);
    void setC (int);
 
    string getArt();
    string getInfo();
    int getX();
    int getC();
 
    int getInvoiceAmount();
private:
    string art, info;
    int x, c;
};
 
#endif

Ну и программка

C++
1
2
3
4
5
6
7
8
#include "invoice.h"
#include <iostream>
using namespace std;
 
int main()
{
    Invoice in1(a; a; 1; 2);
}

Вот здесь мне пишет ошибку —

C++
1
Invoice::Invoice(string a; string b; int x; int c)

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



0



DrOffset

16495 / 8988 / 2205

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

Сообщений: 15,611

16.10.2014, 20:31

2

Лучший ответ Сообщение было отмечено zhundik как решение

Решение

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

Вот здесь мне пишет ошибку —

Тут надо вместо точек с запятой просто запятые поставить.

Добавлено через 3 минуты

C++
1
2
3
Invoice::Invoice(string a, string b, int x, int c)
//.......
Invoice in1(a, a, 1, 2);



1



0 / 0 / 1

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

Сообщений: 61

16.10.2014, 20:38

 [ТС]

3

DrOffset, ох я лол Поставил! Только теперь пишет совсем для меня что-то не ясное error: prototype for ‘Invoice::Invoice(std::string, std::string, int, int)’ does not match any in class ‘Invoice’|

Добавлено через 2 минуты
все работает

Добавлено через 36 секунд
DrOffset, Спасибо огромное, разобрался)))



0



DrOffset

16495 / 8988 / 2205

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

Сообщений: 15,611

16.10.2014, 20:38

4

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

теперь пишет совсем для меня что-то не ясное error: prototype for ‘Invoice::Invoice(std::string, std::string, int, int)’ does not match any in class ‘Invoice’|

Ну так присмотрись, действительно такого объявления в классе нет. Вместо него у тебя там объявлен конструктор в двумя параметрами:

C++
1
Invoice( int, int);

Сделай так:

C++
1
Invoice(string a, string b, int x, int c);



0



0 / 0 / 1

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

Сообщений: 61

16.10.2014, 20:45

 [ТС]

5

DrOffset, Вопрос не по теме можно?! Книжка Дейтелов хорошая? Если не читали, то с какой начинали сами?



0



16495 / 8988 / 2205

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

Сообщений: 15,611

16.10.2014, 20:48

6

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

Если не читали, то с какой начинали сами?

Я Страуструпа читал (Язык программирования С++, по-моему первое еще издание), но тут многие говорят, что она тяжелая (лично я так не думаю).
Поэтому посоветую книжку Липпмана (Язык программирования C++. Вводный курс). Дейтелов я не читал.



0



0 / 0 / 1

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

Сообщений: 61

16.10.2014, 20:52

 [ТС]

7

DrOffset,а я начинал(Страуструп Б. — Программирование. Принципы и практика использования C++ ), но застрял где он начинает программировать калькулятор. Где идет считывание лексем, термов, выражений и т.д Вот тут то я и запутался, слишком много всего сразу непонятного и без особого пояснения кода



0



16495 / 8988 / 2205

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

Сообщений: 15,611

16.10.2014, 20:55

8

zhundik, все потому, что эта книжка не учебник. Следовательно читать ее последовательно не нужно. Читать надо там, где идет. Если где-то не идет, то можно переходить к другой главе. Особо ничего не пострадает, т.к. книга написана в расчете на такое прочтение. А потом можно вернуться к непонятному месту.

Но Липпман для начинающих все равно лучше. И ее хватит очень надолго, т.к. там и для среднего уровня программиста достаточно материала.



0



0 / 0 / 1

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

Сообщений: 61

16.10.2014, 21:02

 [ТС]

9

DrOffset, Ладно спасибо) Сейчас все-таки Дейтелов дочитаю, а потом посмотрю, как-то они меня своим ООП уже в 3-й главе заинтересовали А то структурное надоело уже, а программки-то хочется писать побольше))



0



Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error expected unqualified id before token ошибка
  • Error expected unqualified id before switch
  • Error expected unqualified id before string constant extern c
  • Error expected unqualified id before return
  • Error expected unqualified id before public

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии