Error expected primary expression before char

Ошибка "expected primary-expression before 'char'" при объявления переменной C++ Решение и ответ на вопрос 1779959

Adamtotu

0 / 0 / 0

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

Сообщений: 41

1

13.07.2016, 02:08. Показов 13571. Ответов 20

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


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
50
51
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*);
bool login();
 
int main()
{
    loginANDpassword(char*);
    bool login();
    return 0;
}
void loginANDpassword(char* login)
{
    login[80];char password[80];
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a=3)
    {
        cout<<"In this line you can enter your Login.";
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"Now think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;
    
}
bool login()
{
    char login;
    char enterLogin[80];
    cout <<"Enter the Login: ";
    gets(enterLogin);
    if(strcmp(enterLogin,&login))
    {
        cout<<"The entered Login is not correct.n";
        return false;
    }
    return true;
}

Ошибка такая…11 19 E:Новая папкаDev-CppPracticeЧто-то пробую2.cpp [Error] expected primary-expression before ‘char’

Добавлено через 1 минуту
Если не использовать указатели, тогда все работает. Но мне нужно что была ссылка на ЛОг и пароль. Код не доработан. Но я делаю по этапно. ПРошу скажите что за ошибка?

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



0



nimazzzy

Заблокирован

13.07.2016, 02:10

2

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

login[80];

Это массив чего?

Добавлено через 59 секунд

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

loginANDpassword(char*);

А в этот вызов что передается?

Добавлено через 35 секунд

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

bool login();

Это не вызов функции.



0



Adamtotu

0 / 0 / 0

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

Сообщений: 41

13.07.2016, 02:15

 [ТС]

3

nimazzzy, Это массив Указателя. Ибо если написать

C++
1
char login[80]

Тогда не работает. А так хоть одна ошибка.

Добавлено через 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*);
bool login();
 
int main()
{
    loginANDpassword(char*);
    bool login();
    return 0;
}
void loginANDpassword(char* login)
{
    login[80];char password[80];// Сначала я объявляю массивы ЛОгина и пароля.
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)// Вводим тройку что бы начать регистрацию
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a=3)
    {
        cout<<"In this line you can enter your Login.";//Если введено число 3, включается ИФ.. и ввод Логина.
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"Now think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;//Аналогично ПАРОЛь
    
}
bool login()
{
    char login;//вводим переменную которая примет значение Логина из указателя в функцие  loginANDpassword(char* login)
    char enterLogin[80];
    cout <<"Enter the Login: ";
    gets(enterLogin);
    if(strcmp(enterLogin,&login))//Проверка логина..используем ctrcmp для проверки логина
    {
        cout<<"The entered Login is not correct.n";
        return false;
    }
    return true;
}

Что еще не ясно



0



DrOffset

16495 / 8988 / 2205

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

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

13.07.2016, 02:46

4

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

Что еще не ясно

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

Кликните здесь для просмотра всего текста

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
50
51
52
53
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*);
bool login(char const * login); //!!!!
 
int main()
{
    char arrlogin[80]; //!!!!
 
    loginANDpassword(arrlogin);
    login(arrlogin);
    return 0;
}
void loginANDpassword(char* login)
{
    char password[80];// Сначала я объявляю массивы ЛОгина и пароля.
    cout << "Hello! If you want to registration, please enter the number 3.n";
    int a = 0;
    cin >> a;
    while(a != 3)// Вводим тройку что бы начать регистрацию
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a == 3) //!!!!
    {
        cout<<"In this line you can enter your Login.";//Если введено число 3, включается ИФ.. и ввод Логина.
        cout<<"nThink of a Login: ";
        cin >> login;
        cout<<"Your Login: " << login << endl;
    }
    cout<<"Now think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password << endl;//Аналогично ПАРОЛь
 
}
//вводим переменную которая примет значение Логина из указателя в функцие  loginANDpassword(char* login)
bool login(char const * login) //!!!!
{
    char enterLogin[80];
    cout <<"Enter the Login: ";
    cin >> enterLogin;
    if(strcmp(enterLogin, login) != 0)//Проверка логина..используем ctrcmp для проверки логина
    {
        cout<<"The entered Login is not correct.n";
        return false;
    }
    cout<<"The entered Login is ok!n";
    return true;
}

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

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

Это массив Указателя. Ибо если написать

C++
1
char login[80]

Тогда не работает. А так хоть одна ошибка.

Вообще это называется «замаскировал проблему». Количество ошибок вообще не показатель. У тебя может быть их 40 из-за одной строчки кода (по цепочке). Или может быть внешне одна ошибка, а ее исправление приведет ко второй и так до одурения.
Лучше разобраться с синтаксисом получше.



0



0 / 0 / 0

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

Сообщений: 41

13.07.2016, 02:47

 [ТС]

5

nimazzzy, я чет не совсем понял, что ты сделал. Ты добавил константу? а объясни пожалуйста что изменилось.. я вижу что прога заработала. Помоги справиться с этим..



0



16495 / 8988 / 2205

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

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

13.07.2016, 02:50

6

Adamtotu, сделал не он, а я. И я отметил восклицательными знаками то, что исправил. В частности то, на что обратил внимание товарищ nimazzzy в своем сообщении.



0



Adamtotu

0 / 0 / 0

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

Сообщений: 41

13.07.2016, 02:56

 [ТС]

7

Спасиб…сейчас посмотрю

Добавлено через 4 минуты
DrOffset, Помоги пожалуйста что значит это…

C++
1
2
3
4
5
6
7
int main()
{
    char arrlogin[80];//Зачем было вводить этот массив? ХОчу просто понять зачем все это. Ибо я делаю на ум. Хочу разобраться
    loginANDpassword(arrlogin);
    login(arrlogin);
    return 0;
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
bool login(char const* login)
{
    //вводим переменную которая примет значение Логина из указателя в функцие  loginANDpassword(char* login)
    char enterLogin[80];
    cout <<"Enter the Login: ";
    gets(enterLogin);
    if(strcmp(enterLogin,login))//Почему здесь просто login, почему без Амперсанта?
    {
        cout<<"The entered Login is not correct.n";
        return false;
    }
    return true;
}



0



16495 / 8988 / 2205

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

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

13.07.2016, 12:53

8

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

Решение

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

Зачем было вводить этот массив?

Ну тебе ведь нужно куда-то сохранять введенный логин.
При этом требовалось же его передать потом в другую функцию. Таким образом одна функция у тебя занимается вводом логина (и пароля), а другая — проверкой.

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

Почему здесь просто login, почему без Амперсанта?

Потому что у нас уже есть указатель (параметр функции), который содержит адрес первого элемента массива arrlogin.



1



Adamtotu

0 / 0 / 0

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

Сообщений: 41

14.07.2016, 01:23

 [ТС]

9

DrOffset, спасибо)) лайк помог

Добавлено через 35 минут
DrOffset, помоги мне с этим.. я уже усовершенствовал прогу и вот новые сложности…
до усовершенствования

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
50
51
52
53
54
55
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*,char*);
bool loginANDpassword_check(char const* login,char const* password);
int main()
{
    cout<<"Version 1.1n";
    char arrlogin[80];
    char arrPassword[80];
    loginANDpassword(arrlogin,arrPassword);
    loginANDpassword_check(arrlogin,arrPassword);
    return 0;
}
void loginANDpassword(char* login, char* password)
{
    // Сначала я объявляю массивы ЛОгина и пароля.
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)// Вводим тройку что бы начать регистрацию
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a==3)
    {
        cout<<"In this line you can enter your Login.";//Если введено число 3, включается ИФ.. и ввод Логина.
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"nNow think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;//Аналогично ПАРОЛь
    
}
bool loginANDpassword_check(char const* login,char const* password)
{
    char enterLogin[80];
    cout <<"nEnter the Login: ";
    cin>>enterLogin;
    char enterPassword[80];
    cout <<"nEnter the password: ";
    cin>>enterPassword;
    if(strcmp(enterLogin,login)||strcmp(enterPassword,password))
    {
        cout<<"The entered login or password is not correct.";
        return true;
    }
    return false;
}

после усовершенствования..

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
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
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*,char*);
bool loginANDpassword_check(char const* login,char const* password);
void menu();
void miniatureFeature();
int main()
{
    cout<<"Version 1.1n";
    miniatureFeature();
    return 0;
}
void loginANDpassword(char* login, char* password)
{
    // Сначала я объявляю массивы ЛОгина и пароля.
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)// Вводим тройку что бы начать регистрацию
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a==3)
    {
        cout<<"In this line you can enter your Login.";//Если введено число 3, включается ИФ.. и ввод Логина.
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"nNow think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;//Аналогично ПАРОЛь
    
}
bool loginANDpassword_check(char const* login,char const* password)
{
    char enterLogin[80];
    cout <<"nEnter the Login: ";
    cin>>enterLogin;
    char enterPassword[80];
    cout <<"nEnter the password: ";
    cin>>enterPassword;
    if(strcmp(enterLogin,login)||strcmp(enterPassword,password))
    {
        cout<<"The entered login or password is not correct.";
        return true;
    }
    return false;
}
 
void menu()
{
    int choice = 0;
    cout<<"Welcome in the our world!!!n";
    cout<<"1.Registrationn";
    cout<<"2.Exit";
    
    cout<<"Enter the number (1 or 2)";
    cin>> choice;
    switch(choice)
    {
        case 1:loginANDpassword(char* login, char* password);
        case 2:break;
    }
}
void miniatureFeature()
{
    menu();
    char arrlogin[80];
    char arrPassword[80];
    loginANDpassword(arrlogin,arrPassword);
    loginANDpassword_check(arrlogin,arrPassword);
}

E:Новая папкаDev-CppPracticeЧто-то пробую2(1.1).cpp In function ‘void menu()’:
67 27 E:Новая папкаDev-CppPracticeЧто-то пробую2(1.1).cpp [Error] expected primary-expression before ‘char’
67 40 E:Новая папкаDev-CppPracticeЧто-то пробую2(1.1).cpp [Error] expected primary-expression before ‘char’



0



nimazzzy

Заблокирован

14.07.2016, 01:30

10

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

case 1:loginANDpassword(char* login, char* password);

Зачем объявлять типы аргументов при вызове функции?



0



Adamtotu

0 / 0 / 0

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

Сообщений: 41

14.07.2016, 01:33

 [ТС]

11

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

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
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
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*,char*);
bool loginANDpassword_check(char const* login,char const* password);
void menu();
void miniatureFeature();
int main()
{
    cout<<"Version 1.1n";
    miniatureFeature();
    return 0;
}
void loginANDpassword(char* login, char* password)
{
    // Сначала я объявляю массивы ЛОгина и пароля.
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)// Вводим тройку что бы начать регистрацию
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a==3)
    {
        cout<<"In this line you can enter your Login.";//Если введено число 3, включается ИФ.. и ввод Логина.
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"nNow think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;//Аналогично ПАРОЛь
    
}
bool loginANDpassword_check(char const* login,char const* password)
{
    char enterLogin[80];
    cout <<"nEnter the Login: ";
    cin>>enterLogin;
    char enterPassword[80];
    cout <<"nEnter the password: ";
    cin>>enterPassword;
    if(strcmp(enterLogin,login)||strcmp(enterPassword,password))
    {
        cout<<"The entered login or password is not correct.";
        return true;
    }
    return false;
}
 
void menu()
{
    int choice = 0;
    cout<<"Welcome in the our world!!!n";
    cout<<"1.Registrationn";
    cout<<"2.Exit";
    
    cout<<"Enter the number (1 or 2)";
    cin>> choice;
    switch(choice)
    {
        case 1:loginANDpassword();
        case 2:break;
    }
}
void miniatureFeature()
{
    menu();
    char arrlogin[80];
    char arrPassword[80];
    loginANDpassword(arrlogin,arrPassword);
    loginANDpassword_check(arrlogin,arrPassword);
}

E:Новая папкаDev-CppPracticedddd.cpp In function ‘void menu()’:
67 33 E:Новая папкаDev-CppPracticedddd.cpp [Error] too few arguments to function ‘void loginANDpassword(char*, char*)’
16 6 E:Новая папкаDev-CppPracticedddd.cpp [Note] declared here



0



nimazzzy

Заблокирован

14.07.2016, 01:36

12

Ты убрал не только типы, но и сами аргументы.



0



0 / 0 / 0

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

Сообщений: 41

14.07.2016, 01:37

 [ТС]

13

nimazzzy, покажи как нужно написать, если не трудно



0



nimazzzy

Заблокирован

14.07.2016, 01:40

14

Мне не трудно, но я предпочту подождать, пока ты соизволишь немного разобраться с синтаксисом языка. Тем более, что примеры правильных вызовов у тебя есть.
Либо пока просто кто-то не придет и не напишет тебе.



1



0 / 0 / 0

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

Сообщений: 41

14.07.2016, 01:43

 [ТС]

15

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



0



nimazzzy

Заблокирован

14.07.2016, 10:12

16

Тебе самому не кажется странным, что у тебе в коде есть вызов

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

loginANDpassword(arrlogin,arrPassword);

, а сейчас ты пытаешься сделать

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

loginANDpassword(char* login, char* password);

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

loginANDpassword();

Почему все так по-разному? Даже с точки зрения логики, а не языка…

Добавлено через 32 секунды

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

Я дошел до темы указатели.

Надо пройти тему функции.



0



Adamtotu

0 / 0 / 0

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

Сообщений: 41

14.07.2016, 16:29

 [ТС]

17

nimazzzy, Так ты и не ответил ..

C++
1
2
3
4
5
switch(choice)
    {
        case 1:loginANDpassword();// Что мне здесь написать?
        case 2:break;
    }



0



nimazzzy

Заблокирован

14.07.2016, 22:29

18

Передай функции 2 аргумента, как у тебя уже есть в коде.

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

Так ты и не ответил ..

Да, я хочу, чтобы ты понял.

Добавлено через 5 часов 42 минуты
Ладно, раз ты хочешь подсказку. Ты не можешь вызвать функцию loginANDpassword из функции menu, потому что у тебя нет никаких переменных, которые ты бы мог вообще в нее передать. Ты объявил ее так:

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

bool loginANDpassword_check(char const* login,char const* password);

То есть, она принимает два параметра. Если убрать исходный код, то что ты человеческим языком хочешь в эту функцию передать? И где это «что-то» в функции menu, из которой идет вызов?



0



Adamtotu

0 / 0 / 0

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

Сообщений: 41

14.07.2016, 22:55

 [ТС]

19

nimazzzy,
Вот видишь ты дал подсказку и у меня получилось))) спасиб. Теперь помоги со следующей проблемой. Как мне завершить прогу, если чувак нажмет 2 а не 1. Я пробовал много разных команд..kbhit…цикл for, continue,break,goto. Не знаю как это сделать…

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
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
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
 
void loginANDpassword(char*,char*);
bool loginANDpassword_check(char const* login,char const* password);
void menu();
void miniatureFeature();
int main()
{
    cout<<"Version 1.2n";
    miniatureFeature();
    return 0;
}
void loginANDpassword(char* login, char* password)
{
    // ??????? ? ???????? ??????? ?????? ? ??????.
    cout<<"Hello! If you want to registration, please enter the number 3.n";
    int a;
    cin>>a;
    while(a!=3)// ?????? ?????? ??? ?? ?????? ???????????
    {
        cout<<"It's not correct, please enter the number 3.nn";
        cin>>a;
    }
    if(a==3)
    {
        cout<<"In this line you can enter your Login.";//???? ??????? ????? 3, ?????????? ??.. ? ???? ??????.
        cout<<"nThink of a Login: ";
        cin>>login;
        cout<<"Your Login: "<<login;
        
    }
    cout<<"nNow think of a password: ";
    cin>>password;
    cout<<"Your Password: "<<password;//?????????? ??????
    
}
bool loginANDpassword_check(char const* login,char const* password)
{
    char enterLogin[80];
    cout <<"nEnter the Login: ";
    cin>>enterLogin;
    char enterPassword[80];
    cout <<"nEnter the password: ";
    cin>>enterPassword;
    if(strcmp(enterLogin,login)||strcmp(enterPassword,password))
    {
        cout<<"The entered login or password is not correct.";
        return true;
    }
    return false;
}
 
void menu()
{
    int choice;
    char bLogin[80];
    char bPassword[80];
    cout<<"Welcome in the our world!!!n";
    cout<<"1.Registrationn";
    cout<<"2.Exit";
    
    cout<<"Enter the number (1 or 2)";
    cin>> choice;
    switch(choice)
    {
        case 1:loginANDpassword(bLogin, bPassword);
        case 2:break;
    }
}
void miniatureFeature()
{
    menu();
    char arrlogin[80];
    char arrPassword[80];
    loginANDpassword(arrlogin,arrPassword);
    loginANDpassword_check(arrlogin,arrPassword);
}



0



nimazzzy

Заблокирован

14.07.2016, 23:28

20

Есть exit.



1



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

14.07.2016, 23:28

20

Date class with member functions
Any help would be appreciated.
A few of my errors

C:Dev-CppTemplatesDate2.0.cpp In function `int main()’:
18 C:Dev-CppTemplatesDate2.0.cpp expected primary-expression before «char»
18 C:Dev-CppTemplatesDate2.0.cpp expected `;’ before «char»
23 C:Dev-CppTemplatesDate2.0.cpp expected primary-expression before «char»
23 C:Dev-CppTemplatesDate2.0.cpp expected `;’ before «char»
Part of my code

// This program demonstrates the Date class.
#include <iostream>
#include <cctype>
#include <iomanip>
using namespace std;

// Function prototypes
void displayMenu();

int main()
{
char choice; //Menu Selection
int dd, mm, yy, yyyy;

// Display the menu and get a valid selection.
displayMenu();
cin >> char choice;
while (toupper(choice) < ‘1’ || toupper(choice) > ‘4’)
{
cout << «Please choose a date format «
<< «of 1, 2, 3, 4:»;
cin >> char choice;
}

// Process the user’s menu selection.
switch(choice)
{
case ‘1’: cout << «00/00/00»;
break;
case ‘2’: cout << «Month 00, 0000 «;
break;
case ‘3’: cout << «00 Month, 0000»;
break;
case ‘4’: cout << «End Program
}
} while (touper(choice) != ‘4’);

do
{
if (choice = 1)
cout<< «Enter the Monthn»;
cin>> mm;
do
{
if (mm < 1)
if (mm > 12)
cout<<«ERROR INVALID n»;

cout<< «Enter the Dayn»;
cin>> dd;
do
{
if (dd < 1)
if (dd > 31)
cout<<«ERROR INVALID n»;

cout<< «Enter the Yearn»;
cin>> yy;

cout<<mm<<‘/'<<dd<<‘/’yy<<«;
do
{
if (choice = 2)
cout<< «Enter the Monthn»;
cin>> mm;
do
{
if (mm = 1)
return January
if (mm = 2)
return February
if (mm = 3)
return March
if (mm = 4)
return April
if (mm = 5)
return May
if (mm = 6)
return June
if (mm = 7)
return July
if (mm = 8)
return August
if (mm = 9)
return September
if (mm = 10)
return October
if (mm = 11)
return November
if (mm = 12)
return December
do
{
if
cout<< «Enter the Dayn»;
cin>> dd;
do
{
if (dd < 1)
if (dd > 31)
cout<<«ERROR INVALID n»;

cout<< «Enter the Yearn;
cin>> yy;

cin >> char choice; to cin >> choice; in line 18 and 23

Cool. Thanks for the assist.

if (choice = 1) is wrong ..
it should be if (choice = = 1)

You havent closed any of the do loop.

@bluecoder : No space between = and = , should be «==» (without quotes)

Содержание

  1. Error expected primary expression before char
  2. Thread: expected primary-expression before «char»
  3. expected primary-expression before «char»
  4. Re: expected primary-expression before «char»
  5. Re: expected primary-expression before «char»
  6. Re: expected primary-expression before «char»
  7. Re: expected primary-expression before «char»
  8. Re: expected primary-expression before «char»
  9. Fix “Expected Primary-Expression Before” in C++ or Arduino
  10. How to fix “Expected Primary-Expression Before” error?
  11. Type 1: Expected primary-expression before ‘>’ token
  12. Type 2: Expected primary expression before ‘)’ token
  13. Type 3: Expected primary-expression before ‘enum’
  14. Type 4: Expected primary expression before ‘.’
  15. Type 5: Expected primary-expression before ‘word’
  16. Type 6: Expected primary-expression before ‘else’
  17. Conclusion
  18. ошибка: ожидаемое первичное выражение до токена ‘=’ и многие другие
  19. Решение
  20. Другие решения
  21. Error expected primary expression before char

Error expected primary expression before char

Date class with member functions
Any help would be appreciated.
A few of my errors

C:Dev-CppTemplatesDate2.0.cpp In function `int main()’:
18 C:Dev-CppTemplatesDate2.0.cpp expected primary-expression before «char»
18 C:Dev-CppTemplatesDate2.0.cpp expected `;’ before «char»
23 C:Dev-CppTemplatesDate2.0.cpp expected primary-expression before «char»
23 C:Dev-CppTemplatesDate2.0.cpp expected `;’ before «char»
Part of my code

// This program demonstrates the Date class.
#include
#include
#include
using namespace std;

// Function prototypes
void displayMenu();

int main()
<
char choice; //Menu Selection
int dd, mm, yy, yyyy;

// Display the menu and get a valid selection.
displayMenu();
cin >> char choice;
while (toupper(choice) ‘4’)
<
cout > char choice;
>

// Process the user’s menu selection.
switch(choice)
<
case ‘1’: cout > mm;
do
<
if (mm 12)
cout > dd;
do
<
if (dd 31)
cout > yy;

cout > mm;
do
<
if (mm = 1)
return January
if (mm = 2)
return February
if (mm = 3)
return March
if (mm = 4)
return April
if (mm = 5)
return May
if (mm = 6)
return June
if (mm = 7)
return July
if (mm = 8)
return August
if (mm = 9)
return September
if (mm = 10)
return October
if (mm = 11)
return November
if (mm = 12)
return December
do
<
if
cout > dd;
do
<
if (dd 31)
cout > yy;

Источник

Thread: expected primary-expression before «char»

Thread Tools
Display

expected primary-expression before «char»

hi,
I am new in linux code compiling and i use cygwin.
I ran into Vocab.cc: In member function `VocabIndex Vocab::metaTagOfType(unsigned int)’: Vocab.cc:259: error: expected primary-expression before «char» error.
Can anyone help me to handle this error?

Here is the Vocab.cc:

Re: expected primary-expression before «char»

Pay attention to the error.
Here’s line 259:

You can’t pass a type as an argument (or is it a macro?) Did you omit a «sizeof» here?
Is this function from your Array.cc?

Last edited by gmargo; June 26th, 2011 at 02:36 PM .

Re: expected primary-expression before «char»

yes you are right but unfortunately this is not my code. i download it from a scientific site with free license: http://userver.ftw.at/

pucher/semanlm/semanlm0.91.zip
I checked all the files but there is no definition for makeArray I am confused.
I checked in Array.cc but there is nothing
here is the array.cc:

Re: expected primary-expression before «char»

Somehow you are mixing and matching sources. There is no Vocab.cc in that .zip file. The Vocab.cc file is present in the SRI download available from http://www.speech.sri.com/projects/srilm/

«makeArray» is a macro in the dstruct/src/Array.h file from the SRI sources.

Re: expected primary-expression before «char»

hi gamargo. that was so helpful and replacing the file fixes the error.
I changed the

I copy the entire LHash.cc and I colorized the important lines for the error:

Last edited by andereasmehdi; June 26th, 2011 at 07:16 PM .

Re: expected primary-expression before «char»

If you compare files of the same name in the two source trees, it is obvious that the semanlm code was derived from a much earlier version of the srilm code.

You may have a lot of difficultly combining the two. Or you might try to download older srilm versions to find the matching one. Good luck.

Источник

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.

Источник

ошибка: ожидаемое первичное выражение до токена ‘=’ и многие другие

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

и это часть моего кода:

У меня есть много подобных ошибок во всем коде, поэтому я думаю, что есть что-то вроде пропуска столбца или чего-то другого. Вы видите это? Я не.

Решение

Макрос не является переменной. Это не имеет значения. Это функция предварительной обработки.

Причина, по которой у вас везде появляются синтаксические ошибки, заключается в том, что ERR_OK и тому подобное были заменены = 0; скорее, чем 0 например.

Другие решения

Другие ответы верны, что проблема заключается в символических константах

Тем не менее, в C ++ есть лучший способ исправить это:

Или C и C ++ оба позволяют

Ваш #define s неверны, они должны выглядеть следующим образом, например:

То есть они не должны иметь = и не заканчивается точкой с запятой. #define это директива препроцессора. Они не подчиняются тем же правилам синтаксиса, что и остальная часть C ++. В частности, директива препроцессора завершается новой строкой, а не точкой с запятой.

Это на самом деле определяет ERR_PARAMS быть = 1; , Если потом заменить ERR_PARAMS с = 1; в своем коде вы увидите, почему всплывают некоторые ошибки. Например, рассмотрим эту строку:

Если вы замените ERR_PARAMS здесь вы получите:

Источник

Error expected primary expression before char

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:

Now I want to use the function I wrote:

What you do wrong in the main function:

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

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

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().

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

output: refers to line 32 in this post.

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:

Источник

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.

Code:

 OBJ_READMATRIX= LHash.o Map.o zio.o Array.o File.o Vocab.o option.o ngram-count.o

Vocab.o:Vocab.cc: .text$_ZN5LHashIjjE6removeEjRb[LHash<unsigned int, unsigned int>::remove(unsigned int, bool&)]+0xb): undefined reference to `LHash<unsigned int, unsigned int>::removedData’
Vocab.o:Vocab.cc: ).text$_ZN5LHashIjjE6removeEjRb[LHash<unsigned int, unsigned int>::remove(unsigned int, bool&)]+0x22): undefined reference to `LHash<unsigned int, unsigned int>::removedData’
Vocab.o:Vocab.cc: ).text$_ZN5LHashIjjE6removeEjRb[LHash<unsigned int, unsigned int>::remove(unsigned int, bool&)]+0x106): undefined reference to `LHash<unsigned int, unsigned int>::removedData’
Vocab.o:Vocab.cc: ).text$_ZN5LHashIjjE6removeEjRb[LHash<unsigned int, unsigned int>::remove(unsigned int, bool&)]+0x22b): undefined reference to `LHash<unsigned int, unsigned int>::removedData’

Code:

/*
 * LHash.cc --
 *    Linear search hash table implementation
 *
 */

#ifndef _LHash_cc_
#define _LHash_cc_

#ifndef lint
static char LHash_Copyright[] = "Copyright (c) 1995-2010 SRI International.  All Rights Reserved.";
static char LHash_RcsId[] = "@(#)$Header: /home/srilm/devel/dstruct/src/RCS/LHash.cc,v 1.53 2010/06/02 04:52:43 stolcke Exp $";
#endif

#ifdef PRE_ISO_CXX
# include <new.h>
# include <iostream.h>
#else
# include <new>
# include <iostream>
using namespace std;
#endif
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "C:cygwinsemanlmincludesrilmLHash.h"

#undef INSTANTIATE_LHASH
#define INSTANTIATE_LHASH(KeyT, DataT) 
    template <> DataT *LHash< KeyT, DataT >::removedData = 0; 
    template class LHash< KeyT, DataT >; 
    template class LHashIter< KeyT, DataT >

#ifndef __GNUG__
template <class KeyT, class DataT>
DataT *LHash<KeyT,DataT>::removedData = 0;
#endif /* __GNUG__ */

#ifdef DEBUG
template <class KeyT, class DataT>
unsigned long LHash<KeyT,DataT>::collisionCount = 0;
#endif

const unsigned minHashBits = 3;        /* minimum no. bits for hashing
                     * tables smaller than this use linear
                     * search to save space */
const float fillRatio = 0.8f;        /* fill ration at which the table is
                     * expanded and rehashed */

#define BODY(b)    ((LHashBody<KeyT,DataT> *)b)

/*
 * Dump the entire hash array to cerr.  Unused slots are printed as "FREE".
 */
template <class KeyT, class DataT>
void
LHash<KeyT,DataT>::dump() const
{
    if (body) {
    unsigned maxEntries = hashSize(BODY(body)->maxBits);
    unsigned i;

    for (i = 0; i < maxEntries; i++) {
        cerr << " " << i << ": ";
        if (Map_noKeyP(BODY(body)->data[i].key)) {
        cerr << "FREE";
        } else {
        cerr << BODY(body)->data[i].key
#ifdef DUMP_VALUES
            /* 
             * Only certain types can be printed.
             */
             << "->" << BODY(body)->data[i].value
#endif /* DUMP_VALUES */
             ;
        }
    }
    } else {
    cerr << "EMPTY";
    }
    cerr << endl;
}

template <class KeyT, class DataT>
void
LHash<KeyT,DataT>::memStats(MemStats &stats) const
{
    stats.total += sizeof(*this);
    if (body) {
        unsigned maxEntries = hashSize(BODY(body)->maxBits);

    stats.total += sizeof(*BODY(body)) +
            sizeof(BODY(body)->data[0]) *
                (maxEntries - 1);
    stats.wasted += sizeof(BODY(body)->data[0]) *
                (maxEntries - BODY(body)->nEntries);
    }
}

/*
 * Compute the actual minimum size required for a given number of entries
 */
static inline unsigned
roundSize(unsigned size)
{
    if (size < hashSize(minHashBits)) {
    return size;
    } else {
    return (unsigned)((size + 1)/ fillRatio);
    }
}

template <class KeyT, class DataT>
void
LHash<KeyT,DataT>::alloc(unsigned size)
{
    unsigned maxBits, maxEntries;
    unsigned i;

    /*
     * round up to power of two
     */
    maxBits = 0;
    while (hashSize(maxBits) < size) {
    assert(maxBits < LHash_maxBitLimit);
    maxBits++;
    }

    maxEntries = hashSize(maxBits);

    //cerr << "LHash::alloc: current " << (body ? BODY(body)->nEntries : 0)
    //     << ", requested " << size 
    //     << ", allocating " << maxEntries << " (" << maxBits << ")n";

    body = (LHashBody<KeyT,DataT> *)malloc(sizeof(*BODY(body)) +
                   (maxEntries - 1) * sizeof(BODY(body)->data[0]));
    assert(body != 0);

    BODY(body)->maxBits = maxBits;
    BODY(body)->nEntries = 0;

    for (i = 0; i < maxEntries; i++) {
    Map_noKey(BODY(body)->data[i].key);
    }
    //cerr << "memory for header = " <<
    //        ((void *)&(BODY(body)->data[0]) - (void *)BODY(body)) << endl;
    //cerr << "memory per entry = " <<
    //        ((void *)&(BODY(body)->data[3]) - (void *)&(BODY(body)->data[2])) << endl;
}

template <class KeyT, class DataT>
LHash<KeyT,DataT>::LHash(unsigned size)
    : body(0)
{
    if (size != 0) {
    /*
     * determine actual initial size
     */
    alloc(roundSize(size));
    }
}

template <class KeyT, class DataT>
void
LHash<KeyT,DataT>::clear(unsigned size)
{
    if (body) {
    unsigned maxEntries = hashSize(BODY(body)->maxBits);
    unsigned i;

    for (i = 0; i < maxEntries; i++) {
        if (! Map_noKeyP(BODY(body)->data[i].key)) {
        Map_freeKey(BODY(body)->data[i].key);
        }
    }
    free(body);
    body = 0;
    }
    if (size != 0) {
    alloc(roundSize(size));
    }
}

template <class KeyT, class DataT>
void LHash<KeyT,DataT>::setsize(unsigned size)
{
    if (body == 0 && size != 0) {
    alloc(roundSize(size));
    }
}

template <class KeyT, class DataT>
LHash<KeyT,DataT>::~LHash()
{
    clear(0);
}

template <class KeyT, class DataT>
LHash<KeyT,DataT>::LHash(const LHash<KeyT,DataT> &source)
    : body(0)
{
#ifdef DEBUG
    cerr << "warning: LHash copy constructor calledn";
#endif
    *this = source;
}

template <class KeyT, class DataT>
LHash<KeyT,DataT> &
LHash<KeyT,DataT>::operator= (const LHash<KeyT,DataT> &other)
{
#ifdef DEBUG
    cerr << "warning: LHash::operator= calledn";
#endif

    if (&other == this) {
    return *this;
    }

    /*
     * copy hash entries from old to new 
     */
    if (other.body) {
    unsigned maxEntries = hashSize(BODY(other.body)->maxBits);
    /*
     * ensure we have exactly the same size as source table
     */
    clear(0);
    alloc(maxEntries);

    for (unsigned i = 0; i < maxEntries; i++) {
        KeyT thisKey = BODY(other.body)->data[i].key;

        if (!Map_noKeyP(thisKey)) {
        /*
         * Copy key
         */
        BODY(body)->data[i].key = Map_copyKey(thisKey);

        /*
         * Initialize data, required for = operator
         */
        new (&(BODY(body)->data[i].value)) DataT;

        /*
         * Copy data
         */
        BODY(body)->data[i].value = BODY(other.body)->data[i].value;
        }
    }
    BODY(body)->nEntries = BODY(other.body)->nEntries;
    } else {
    clear(0);
    }

    return *this;
}

/*
 * Returns index into data array that has the key which is either
 * equal to key, or indicates the place where key would be placed if it
 * occurred in the array.
 */
template <class KeyT, class DataT>
Boolean
LHash<KeyT,DataT>::locate(KeyT key, unsigned &index) const
{
    assert(!Map_noKeyP(key));

    if (body) {
    unsigned maxBits = BODY(body)->maxBits;
        register MapEntry<KeyT,DataT> *data = BODY(body)->data;

    if (maxBits < minHashBits) {
        /*
         * Do a linear search
         */
        unsigned nEntries = BODY(body)->nEntries;
        register unsigned i;

        for (i = 0; i < nEntries; i++) {
        if (LHash_equalKey(data[i].key, key)) {
            index = i;
            return true;
        }
        }
        index = i;
        return false;
    } else {
        /*
         * Do a hashed search
         */
        unsigned hash = LHash_hashKey(key, maxBits);
        unsigned i;

        for (i = hash; ; i = (i + 1) & hashMask(maxBits))
        {
        if (Map_noKeyP(data[i].key)) {
            index = i;
            return false;
        } else if (LHash_equalKey(data[i].key, key)) {
            index = i;
            return true;
        }
#ifdef DEBUG
        collisionCount += 1;
#endif
        }
    }
    } else {
    return false;
    }
}

template <class KeyT, class DataT>
DataT *
LHash<KeyT,DataT>::find(KeyT key, Boolean &foundP) const
{
    unsigned index;

    if ((foundP = locate(key, index))) {
    return &(BODY(body)->data[index].value);
    } else {
    return 0;
    }
}

template <class KeyT, class DataT>
KeyT
LHash<KeyT,DataT>::getInternalKey(KeyT key, Boolean &foundP) const
{
    unsigned index;
    static KeyT zeroKey;

    if ((foundP = locate(key, index))) {
    return BODY(body)->data[index].key;
    } else {
    return zeroKey;
    }
}

template <class KeyT, class DataT>
DataT *
LHash<KeyT,DataT>::insert(KeyT key, Boolean &foundP)
{
    unsigned index;

    assert(!(Map_noKeyP(key)));

    /*
     * Make sure there is room for at least one entry
     */
    if (body == 0) {
    alloc(1);
    }

    if ((foundP = locate(key, index))) {
    return &(BODY(body)->data[index].value);
    } else {
    unsigned maxEntries = hashSize(BODY(body)->maxBits);
    unsigned nEntries = BODY(body)->nEntries;

    /*
     * Rehash table if necessary
     */
    unsigned minSize = roundSize(nEntries + 1);

    if (minSize > maxEntries) {
        LHashBody<KeyT,DataT> *oldBody = BODY(body);
        unsigned i;

        /*
         * Since LHash_maxEntriesLimit is a power of two minus 1
         * we need to check this only when the array is enlarged
         */
        assert(nEntries < LHash_maxEntriesLimit);

        alloc(minSize);
        BODY(body)->nEntries = nEntries;

        if (BODY(body)->maxBits < minHashBits) {
        /*
         * Just copy old entries to new storage, no reindexing
         * required.
         */
        memcpy(BODY(body)->data, oldBody->data,
            sizeof(oldBody->data[0]) * nEntries);
        } else {
        /*
         * Rehash
         */
        for (i = 0; i < maxEntries; i++) {
            KeyT key = oldBody->data[i].key;

            if (! Map_noKeyP(key)) {
            (void)locate(key, index);
            memcpy(&(BODY(body)->data[index]), &(oldBody->data[i]),
                            sizeof(oldBody->data[0]));
            }
        }
        }
        free(oldBody);

        /*
         * Entries have been moved, so have to re-locate key
         */
        (void)locate(key, index);
    }

    BODY(body)->data[index].key = Map_copyKey(key);

    /*
     * Initialize data to zero, but also call constructors, if any
     */
    memset(&(BODY(body)->data[index].value), 0,
            sizeof(BODY(body)->data[index].value));
    new (&(BODY(body)->data[index].value)) DataT;

    BODY(body)->nEntries++;

    return &(BODY(body)->data[index].value);
    }
}

template <class KeyT, class DataT>
DataT *
LHash<KeyT,DataT>::remove(KeyT key, Boolean &foundP)
{
    unsigned index;

    /*
     * Allocate pseudo-static memory for removed objects (returned by
     * remove()). We cannot make this static because otherwise 
     * the destructor for DataT would be called on it at program exit.
     */
    if (removedData == 0) {
    removedData = (DataT *)malloc(sizeof(DataT));
    assert(removedData != 0);
    }

    if ((foundP = locate(key, index))) {
    Map_freeKey(BODY(body)->data[index].key);
    Map_noKey(BODY(body)->data[index].key);
    memcpy(removedData, &BODY(body)->data[index].value, sizeof(DataT));

    if (BODY(body)->maxBits < minHashBits) {
        /*
         * Linear search mode -- Just move all entries above the
         * the one removed to fill the gap.
         */
        unsigned nEntries = BODY(body)->nEntries;

        memmove(&BODY(body)->data[index],
            &BODY(body)->data[index+1],
            (nEntries - index - 1) * sizeof(BODY(body)->data[0]));
        Map_noKey(BODY(body)->data[nEntries - 1].key);
    } else {
        /*
         * The entry after the one being deleted could actually
         * belong to a prior spot in the table, but was bounced forward due
         * to a collision.   The invariant used in lookup is that
         * all locations between the hash index and the actual index are
         * filled.  Hence we examine all entries between the deleted
         * position and the next free position as whether they need to
         * be moved backward.
         */
        while (1) {
        unsigned newIndex;

        index = (index + 1) & hashMask(BODY(body)->maxBits);

        if (Map_noKeyP(BODY(body)->data[index].key)) {
            break;
        }

        /* 
         * If find returns false that means the deletion has
         * introduced a hole in the table that would prevent
         * us from finding the next entry. Luckily, find 
         * also tells us where the hole is.  We move the 
         * entry to its rightful place and continue filling
         * the hole created by this move.
         */
        if (!locate(BODY(body)->data[index].key, newIndex)) {
            memcpy(&(BODY(body)->data[newIndex]),
               &(BODY(body)->data[index]),
               sizeof(BODY(body)->data[0]));
            Map_noKey(BODY(body)->data[index].key);
        }
        }
    }
    BODY(body)->nEntries--;
    return removedData;
    } else {
    return 0;
    }
}

#ifdef __GNUG__
static
#endif
int (*LHash_thisKeyCompare)();        /* used by LHashIter() to communicate
                     * with compareIndex() */
#ifdef __GNUG__
static
#endif
void *LHash_thisBody;            /* ditto */

template <class KeyT, class DataT>
void
LHashIter<KeyT,DataT>::sortKeys()
{
    /*
     * Store keys away and sort them to the user's orders.
     */
    unsigned maxEntries = hashSize(myLHashBody->maxBits);

    unsigned *sortedIndex = new unsigned[numEntries];
    assert(sortedIndex != 0);

    unsigned i;

    unsigned j = 0;
    for (i = 0; i < maxEntries; i++) {
    if (!Map_noKeyP(myLHashBody->data[i].key)) {
        sortedIndex[j++] = i;
    }
    }
    assert(j == numEntries);

    /*
     * Due to the limitations of the qsort interface we have to 
     * pass extra information to compareIndex in these global
     * variables - yuck. 
     */
    LHash_thisKeyCompare = (int(*)())sortFunction;
    LHash_thisBody = myLHashBody;
    qsort(sortedIndex, numEntries, sizeof(*sortedIndex), compareIndex);

    /*
     * Save the keys for enumeration.  The reason we save the keys,
     * not the indices, is that indices may change during enumeration
     * due to deletions.
     */
    sortedKeys = new KeyT[numEntries];
    assert(sortedKeys != 0);

    for (i = 0; i < numEntries; i++) {
    sortedKeys[i] = myLHashBody->data[sortedIndex[i]].key;
    }

    delete [] sortedIndex;
}

template <class KeyT, class DataT>
LHashIter<KeyT,DataT>::LHashIter(const LHash<KeyT,DataT> &lhash,
                    int (*keyCompare)(KeyT, KeyT))
    : myLHashBody(BODY(lhash.body)), current(0),
      numEntries(lhash.numEntries()), sortFunction(keyCompare)
{
    /*
     * Note: we access the underlying LHash through the body pointer,
     * not the top-level LHash itself.  This allows the top-level object
     * to be moved without affecting an ongoing iteration.
     * XXX: This only works because
     * - it is illegal to insert while iterating
     * - deletions don't cause reallocation of the data
     */
    if (sortFunction && myLHashBody) {
    sortKeys();
    } else {
    sortedKeys = 0;
    }
}

/*
 * This is the callback function passed to qsort for comparing array
 * entries. It is passed the indices into the data array, which are
 * compared according to the user-supplied function applied to the 
 * keys found at those locations.
 */
template <class KeyT, class DataT>
int
LHashIter<KeyT,DataT>::compareIndex(const void *idx1, const void *idx2)
{
    return (*(compFnType)LHash_thisKeyCompare)
            (BODY(LHash_thisBody)->data[*(unsigned *)idx1].key,
             BODY(LHash_thisBody)->data[*(unsigned *)idx2].key);
}

template <class KeyT, class DataT>
LHashIter<KeyT,DataT>::~LHashIter()
{
    delete [] sortedKeys;
}


template <class KeyT, class DataT>
void 
LHashIter<KeyT,DataT>::init()
{
    delete [] sortedKeys;

    current = 0;

    {
    /*
     * XXX: fake LHash object to access numEntries()
     */
    LHash<KeyT,DataT> myLHash(0);

    myLHash.body = myLHashBody;
    numEntries = myLHash.numEntries();
    myLHash.body = 0;
    }

    if (sortFunction && myLHashBody) {
    sortKeys();
    } else {
    sortedKeys = 0;
    }
}

template <class KeyT, class DataT>
DataT *
LHashIter<KeyT,DataT>::next(KeyT &key)
{

    if (myLHashBody == 0) {
    return 0;
    } else {
    unsigned index;

    if (sortedKeys) {
        /*
         * Sorted enumeration -- advance to next key in sorted list
         */
        if (current == numEntries) {
        return 0;
        }

        /*
         * XXX: fake LHash object to access locate()
         */
        LHash<KeyT,DataT> myLHash(0);

        myLHash.body = myLHashBody;
        myLHash.locate(sortedKeys[current++], index);
        myLHash.body = 0;;
    } else {
        /*
         * Detect deletions by comparing old and current number of 
         * entries.
         * A legal deletion can only affect the current entry, so
         * adjust the current position to reflect the next entry was
         * moved.
         */
        if (myLHashBody->nEntries != numEntries) {
        assert(myLHashBody->nEntries == numEntries - 1);

        numEntries --;
        current --;
        }

        /*
         * Random enumeration mode
         */
        unsigned maxBits = myLHashBody->maxBits;

        if (maxBits < minHashBits) {
        /*
         * Linear search mode - advance one to the next entry
         */
        if (current == numEntries) {
            return 0;
        }
        } else {
        unsigned maxEntries = hashSize(maxBits);

        while (current < maxEntries &&
               Map_noKeyP(myLHashBody->data[current].key))
        {
            current++;
        }

        if (current == maxEntries) {
            return 0;
        }
        }

        index = current ++;
    }

    key = myLHashBody->data[index].key;
    return &(myLHashBody->data[index].value);
    }
}

#undef BODY

#endif /* _LHash_cc_ */

#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
class name{
char* name_store;

public:
void setname(char*);
void displayname(char*);
};

void name::setname(char* nm){
name_store=nm;
}
void displayname(char* name_store){
cout<<«the name: «<<name_store;
}

main()
{
char nm[20];
name n;
cout<<» enter a name «;
cin>>nm;
n.setname(» «);
n.displayname(char* name_store); //getting the error at this line//
system(«pause»);
return (0);
}

Explain, out loud, in english, what that line is supposed to do, and you’ll get it.

it’s sposed to accept a name from the user, store it, and then display the name. but when i call the display function i get the error. i’m new at programming so i’m not sure how to fix it.

no no, I said, that LINE, not that program. Describe what function is being called, what data it expects, and what data you are giving it. In English. OUT LOUD.

Explaining it will not help, as OP hasn’t most probably understood the reason why it isn’t working. As I see it, it has nothing to do with the logic behind the code. The problem is caused because of not knowing the language well enough.

Just out of curiocity, what book are you using to learn from? What language are you programming in? From that code, I can’t quite figure it out. :p

ok so i thought about what u said and i made the adjustments to the line, cause it’s just calling the display function to display the name stored in name_store. it’s not accepting anything, so i realised i had it wrong. but now i’m having the same problem with the function call to the store operation:
n.setname(char* nm);
that function should take in the value from the prompt, and store it to name_store. but when i call it in the main function, it gives me the expected primary-expression before «char» error.

using deitel n deitel 6th edition, how to program c++. ur probly rite, possibly it is caused from not knowing the language well enough, that’s the whole reason am trying to learn it tho. and i’m just getting confused with calling functions that involve characters or strings.

how about…

char* mychar;
//do stuff w mychar
n.displayname(mychar);

where would i put that? should i declare it in the private subsection of the class, or should i put it in main? @ mrchrismnh

There are quite a few errors with that code so I am going to show what it should look like with some notes in the comments:

// iostream.h is an old header file that should no longer be used. // iostream (without the .h) should be used instead#include <iostream>// string is a C++ class that makes handling strings a lot easier and is// less error prone compared to using char arrays#include <string>class name{	std::string name_store;	public:	void setname( const std::string & a_name );	void displayname();};void name::setname( const std::string & a_name ){	name_store = a_name;}void name::displayname(){	std::cout << "the name: " << name_store;	}// Note the return type for mainint main(){	std::string nm;	name n;	std::cout << " enter a name ";	std::cin >> nm;	n.setname(nm);	n.displayname();	return 0;}

Понравилась статья? Поделить с друзьями:
  • Error exited with error code 128
  • Error expected primary expression at end of input
  • Error exit was not declared in this scope
  • Error exit status 1 gmpu
  • Error exit from the fuse process