Error expected initializer before char

Error expected initializer before char I’m writing a class with an array and I’m supposed to calculate the average of some entered grades outside the class and in the main but I get the error Expected Initializer before ‘.’ token I’m not to sure what to do or i even did the class right […]

Содержание

  1. Error expected initializer before char
  2. expected initializer before ‘>’ token #1351
  3. Comments

Error expected initializer before char

I’m writing a class with an array and I’m supposed to calculate the average of some entered grades outside the class and in the main but I get the error
Expected Initializer before ‘.’ token

I’m not to sure what to do or i even did the class right
Please help!

What if I promised you $1000, but then just walk away, leaving you empty handed?
You make a promise on line 24, but you don’t keep it.

The error is on line 44. Please explain this code:
float gradeAverage.getGrade();

Line 44 looks like a nice prototype, but what is it doing in the middle of the program?

In the function «getGrade()» Why are you printing the array when you should be returning something from the array. In this case the «getGrade()» function should have a parameter the represents the element of the array that you need.

As you have it «float getGrade ()» would be better named «void printGrades ()».

Hope that helps,

I know that i shouldn’t be printing the there but the question was my teacher gave me was this
Write a class called Student that contains a property called grades that can store a
maximum of 10 grades. Create a setter and a getter method. The setter method
will take no parameters and return no parameters. Instead, within the setter
method you must construct a loop that will ask the user to enter 10 grades. The
getter method will simply print the 10 grades; so, it will take no and return no
parameters. Yes, that is a misnomer; this is because passing and returning arrays
has not been covered yet. Create another method called computeAverage that
return the average of all the grades. Create another method called
minimumGrade that returns the minimum grade the student received.

He knows it’s a misnomer but he wants us to do it anyway.
He hasn’t covered it yet so I was just looking it up but nothing I find helps

Now that I see what is required I will take a look tomorrow and see what I can do.

Источник

expected initializer before ‘>’ token #1351

Hi I’m programming a esp8266 on Arduino but I keep getting this error, how can i solve it?

expected initializer before ‘>’ token

Arduino:1.8.12 (Mac OS X), Scheda:»NodeMCU 0.9 (ESP-12 Module), 80 MHz, Serial, 115200, 4M (3M SPIFFS)»

In file included from sketch/Accesspoints.h:7:0,
from sketch/Accesspoints.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 **buf, int len, bool sys_seq)
^
In file included from sketch/Accesspoints.cpp:1:0:
Accesspoints.h:8:1: error: expected initializer before ‘>’ token
>
^
In file included from sketch/Attack.h:7:0,
from sketch/Attack.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/Attack.h:9:0,
from sketch/Attack.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
In file included from sketch/CLI.h:8:0,
from sketch/CLI.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/CLI.h:10:0,
from sketch/CLI.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
In file included from sketch/Settings.h:7:0,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 **buf, int len, bool sys_seq)
^
In file included from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/../JsonBuffer.hpp:11:0,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/JsonParser.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/JsonBufferBase.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.hpp:9,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.h:9,
from sketch/Settings.h:9,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/../Data/NonCopyable.hpp:7:1: error: expected initializer before ‘namespace’
namespace ArduinoJson <
^
In file included from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.hpp:9:0,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.h:9,
from sketch/Settings.h:9,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp:16:28: error: expected declaration before end of line
#pragma GCC diagnostic push
^
sketch/CLI.cpp: In member function ‘void CLI::load()’:
CLI.cpp:16:52: error: ‘str’ was not declared in this scope
String defaultValue = str(CLI_DEFAULT_AUTOSTART);

sketch/CLI.cpp: In member function ‘uint32_t CLI::getTime(String)’:
CLI.cpp:140:76: error: ‘str’ was not declared in this scope
else if (time.substring(time.length() — 3).equalsIgnoreCase(str(STR_MIN)) ||

sketch/CLI.cpp: In member function ‘void CLI::runCommand(String)’:
CLI.cpp:221:40: error: ‘str’ was not declared in this scope
if (list->get(0) == str(CLI_COMMENT)) <

CLI.cpp:571:47: error: ‘str’ was not declared in this scope
sprintf(s, str(CLI_RICE_OUTPUT).c_str(), i / 10);

CLI.cpp:713:41: error: ‘str’ was not declared in this scope
sprintf(s, str(CLI_SYSTEM_OUTPUT).c_str(), 81920 — system_get_free_heap_size(),

CLI.cpp:1044:60: error: ‘str’ was not declared in this scope
if (i == height) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(),

CLI.cpp:1046:69: error: ‘str’ was not declared in this scope
else if (i == height / 2) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(),

CLI.cpp:1049:60: error: ‘str’ was not declared in this scope
else if (i == 0) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(), 0);

In file included from sketch/LED.h:6:0,
from sketch/LED.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/LED.h:8:0,
from sketch/LED.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
sketch/Attack.cpp: In member function ‘void Attack::status()’:
Attack.cpp:129:25: error: ‘str’ was not declared in this scope
A_STATUS).c_str(), packetRate, deauthPkts, deauth.maxPkts, beaconPkts, beacon.maxPkts, probePkts,
^
sketch/Attack.cpp: In member function ‘bool Attack::sendPacket(uint8_t*, uint16_t, uint8_t, uint16_t)’:
Attack.cpp:412:60: error: ‘wifi_send_pkt_freedom’ was not declared in this scope
bool sent = wifi_send_pkt_freedom(packet, packetSize, 0) == 0;
^
exit status 1
expected initializer before ‘>’ token

The text was updated successfully, but these errors were encountered:

Источник

Update

It seems you are compiling the wrong file. See the following console commands and output (its german, but I think the message is sufficiently similar to yours):

$ rm test1.c 
$ touch test1.c
$ gcc test1.c 
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In Funktion `_start':
(.text+0x20): Nicht definierter Verweis auf `main'
collect2: error: ld returned 1 exit status
$ 

Long story short: you compile the wrong file (probably an empty one) and for that reason you get this error message which is totally unrelated to any of your code.


Original Answer

I’m going to assume a few things about your code, in order to provide you an answer that results in a compilable code — whether the result of running the program means anything is up to you (to be honest, I intentionally suggest changes that won’t give you the program you most probably want, since you need something to learn with).

I start with your main function

int main (void){
   char calcular_vocal(char[]);
}

What you do inside the main function, is writing a declaration of the calcular_vocal function, but with a different function signature than your actual implementation. Change it to void calcular_vocal(char[]); in order to have this part compilable.

Now to the code inside the calcular_vocal function:

The line char vocales[5]="a,e,i,o,u"; is not allowed, because the string size is to big for your array. Increase the array size to 9 or 10 in order to have enough space available: char vocales[9] = "a,e,i,o,u";

Moving on to line int i, vector contadores[5];, assuming you want to have a variable named «vector contadores». You cannot have space in your variable names, so rename it to «vector_contadores» for all occurences in order to make this piece work.

Moving on to all the if-statements. They are all the same, so I only write something about the first one. The code cadena a++; is invalid. You have multiple options to solve this. (1) erase the a from that code (cadena++;). (2) define integer variable for a and remove cadena from the code (a++;). (3) rewrite to cadena['a']++;. There are even more options to make this part compileable.

The variables int max,pos; are defined inside the for-loop but are used outside. Move their definition to the top of the function, where you define your other variables. Also, initialize max with value -1.

This should be all you need to compile this piece of code (unless I forgot something)

BalexD

0 / 0 / 0

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

Сообщений: 16

1

28.12.2013, 21:41. Показов 30160. Ответов 11

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


В общем, компилятор почему-то ругается на 3 строку, говоря «expected initializer before void» Что ему тут не нравится — ума не приложу. Все функции есть в хидере, ругаться стал недавно — ранее работал на ура. Перестраивала, перезапускала блокс(на всяк пожарный), а толку нет. Вот сам код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "HW_C.h"
 
void less_1()
{
    bool flag=true;
    int temp;
    system("clear");
    while(flag)
    {
        printf("nВыберите задание:nt1 Среднее арифметическое двух чиселnt2 Перевод гривны в валютуnt3 Вывод текстаnt4 Квадрат числаnt5 Сумма и произведение трёхnt6 Назадn");
        scanf("%d", &temp);
        system("clear");
        switch(temp)
        {
            case 1: printf("Среднее арифметическое: %.3lfn",arithmetic_average()); break;
            case 2: exchange();break;
            case 3: text();break;
            case 4: printf("%dn", sqr()); break;
            case 5: summ_and_product_of_3();break;
            case 6: flag=false; break;
        }
    }
}

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



0



Модератор

Эксперт С++

12641 / 10135 / 6102

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

Сообщений: 27,170

28.12.2013, 21:48

2

Что-то не так в HW_C.h
Что там написано?



0



Эксперт С++

1672 / 1044 / 174

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

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

28.12.2013, 21:48

3

Логично предположить, что ошибка в файле HW_C.h. Например, отсутствие точки с запятой после определения структуры.



0



17 / 17 / 2

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

Сообщений: 114

28.12.2013, 21:50

4

Что-то в заголовочном файле не так. Покажите нам его, пожалуйста.



0



BalexD

0 / 0 / 0

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

Сообщений: 16

28.12.2013, 22:07

 [ТС]

5

Вот та самая часть хидера:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
 
using namespace std;
 
 
void less_1();
void exchange();
void text();
int sqr();
void summ_and_product_of_3();
double arithmetic_average();
 
void less_2();
bool even_or_odd();
void summ_and_amount();



0



Модератор

Эксперт С++

12641 / 10135 / 6102

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

Сообщений: 27,170

29.12.2013, 11:03

6

У меня это все компилируется.
Возможно перепутали несколько одинаковых HW_C.h
В строчке
#include «HW_C.h»
щелкните правой кнопкой мыши по HW_C.h и выберите
Open HW_C.h (Открытие документа HW_C.h).



0



0 / 0 / 0

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

Сообщений: 16

03.01.2014, 02:07

 [ТС]

7

Проблема в том, что HW_C.h — один-единственный. И других просто нету. Уж не знаю, на что грешить(



0



5493 / 4888 / 831

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

Сообщений: 13,587

03.01.2014, 02:14

8

Весь проект выкладывайте.



0



0 / 0 / 0

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

Сообщений: 16

08.01.2014, 20:02

 [ТС]

9

Ну, кидаю в виде ссылки. Чтоб никто не терялся: сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.



0



5493 / 4888 / 831

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

Сообщений: 13,587

09.01.2014, 04:58

10

Вот результат компиляции этого проекта в Code::Blocks 12.11:

objDebugHW_Dop1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugHW_Dop4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_1.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_2.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_3.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_4.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_5.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugLess_6.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
objDebugmain.o||In function `Z13insert_4_numbv’:|
C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|multiple definition of `insert_4_numb()’|
objDebugHW_Dop.o:C:Documents and SettingsAdministratorDesktopHW_C_mainHW_C_main HW_C.h|73|first defined here|
||=== Build finished: 22 errors, 0 warnings (0 minutes, 4 seconds) ===|

И при чём здесь тогда:

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

компилятор почему-то ругается на 3 строку, говоря «expected initializer before void»

???

Добавлено через 1 минуту
И кто вас научил делать реализацию функции (insert_4_numb()) в заголовочном файле?

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

сама функция используется в HW_Dop1.cpp, а в хидере прописана в самом конце.



1



0 / 0 / 0

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

Сообщений: 16

10.01.2014, 00:02

 [ТС]

11

Хм.. Странно. У меня все выглядит немного по-другому.

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

Но спасибо за указания на промахи. Искренне всем благодарна)



0



5493 / 4888 / 831

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

Сообщений: 13,587

10.01.2014, 00:07

12

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

Хм.. Странно. У меня все выглядит немного по-другому.

Интересно было бы посмотреть.



0



  1. Я пишу пустой код, безо всего, выделяет слово void и выдаёт такую ошибку:

    Arduino: 1.6.8 (Windows 7), Плата:»Arduino/Genuino Uno»

    sketch_may03a:7: error: expected initializer before ‘void’

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void setup()’:

    sketch_may03a:5: error: expected ‘;’ before ‘}’ token

    E:СашаАрдуйноsketch_may03asketch_may03a.ino: In function ‘void loop()’:

    sketch_may03a:10: error: expected ‘;’ before ‘}’ token

    exit status 1
    expected initializer before ‘void’

    Что делать? Скачал программу с официального сайта.

  2. внимательно читать сообщение об ошибке: в функции setup() в строках 5 и 10 отсутствует символ «;» в конце строки.

  3. кто может помочь в этом??

    Вложения:

    • 2016-05-03 (1).png

  4. Не определен объект Audio. Скорее всего отсутствует библиотека или она не включена в программу.

  5. Arduino: 1.6.8 Hourly Build 2016/01/27 03:44 (Windows 10), Плата:»Arduino/Genuino Uno»

    sketch_oct31a:53: error: expected unqualified-id before ‘{‘ token

    sketch_oct31a:61: error: expected declaration before ‘}’ token

    exit status 1
    expected unqualified-id before ‘{‘ token

    This report would have more information with
    «Show verbose output during compilation»
    option enabled in File -> Preferences.

    Помогите! Обьясните что делать?

  6. C:UsersUserDesktoparduino-nightlyhardwarearduinoavrcoresarduino/main.cpp:43: undefined reference to `setup’

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Ошибка компиляции для платы Arduino/Genuino Uno.
    Что за ошибка?

  • Forum
  • General C++ Programming
  • [Error] expected initializer before ‘whi

[Error] expected initializer before ‘while’

I keep receiving this error, nothing I do helps it’s in
line 11, while (again == ‘Y’ || again == ‘Y’) //begins while loop

Help

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
sing std::endl;
using std::showpos; // shows positive symbol on positive integers
#include <string> // allows for string inclusion
using namespace std;


int main()

while  (again == 'Y' || again == 'Y')  //begins while loop

{

double userInput;
char p[5]; "again";
		cout << "Enter Fahrenheit Value: "; // asks for a value to convert
		do // starts the do loop
		{
			cin >> userInput; //user input value
			cout << "n"; // blank line
			if (cin.fail() || (userInput > 213) || (userInput < -147)) // defines the range of acceptable user input values
			{
				cout << "invalid value, please try again: "; // output when unacceptable value is input
				cin.clear(); // clear 
				cin.ignore(); // so output doesn't repeat 
			}

		} while (cin.fail() || (userInput > 213) || (userInput < -147)); // defines acceptable range of user input values

		double celsius;
		celsius = (userInput - 32) *5.0 / 9.0; //sets output formula
		cout << fixed; //enables for spesific decimal precision
		cout << setprecision(2); //sets precision value to 2 points after the decimal
		cout << "n"; //blank line
		cout << internal << showpos << setw(5) << userInput << " Degrees Fahrenheit = " << celsius << " Degrees Celsius. n" << endl << endl; //output display for result calculated with +/- symbol included

		cout << "Would you like to convert more values?" << endl << endl; //asks to continue or not
		cout << "Enter 'Y' to continue." << endl << endl; // requires user input to continue or end program
		cin >> again; //change control variable
		cout << endl; // spacing for viewing ease

	} // ends while loop
system("pause"); //added so user can terminate program

	return 0; //terminates program  

Last edited on

What is there before the while (again == 'Y' || again == 'Y')?
What is the first thing that there should be after main()?

besides int main()
nothing is before while (again == ‘Y’ || again ==’Y’

When I put a brace { before the while statement I end up with a 10 more errors?
This is my first programming class I have never done anything like this and I’m frustrated.

These are the instruction for the program, I have to include all of this and I don’t even know if I have included all of it.

Create the following program which converts Fahrenheit to Celsius. Your program must have the following functions:
•Read integer Fahrenheit temperatures from the user. You need to check whether the input is the correct one or not. If the user enters the incorrect number, ask it again.
•Use the formula: Celsius = (Fahrenheit – 32) * 5.0 / 9.0
•The output Celsius should be a floating point with two digits of precision.
•The Celsius temperatures should be displayed with a sign of positive or negative.
•The program should ask the user to continue or not. If the user wants to do the conversion again, use repetitive statements such as DO WHILE, FOR, or IF THEN ELSE to do the conversion again.
•Add comments to explain the functions of the program.

Last edited on

I have been working on this and this is what I now have, with a set of new errors.
which are [Error] ‘setprecision’ cannot be used as a function
and [Error] ‘setw’ cannot be used as a function

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
int main()

{
int again, setprecision, setw;
while  ( again == 'Y' || again == 'Y');  //begins while loop



double userInput;

		cout << "Enter Fahrenheit Value: "; // asks for a value to convert
		do // starts the do loop
		{
			cin >> userInput ; //user input value
			cout << "n"; // blank line
			if (cin.fail() || (userInput > 213) || (userInput < -147)) // defines the range of acceptable user input values
			{
				cout << "invalid value, please try again: "; // output when unacceptable value is input
				cin.clear(); // clear 
				cin.ignore(); // so output doesn't repeat 
			}

		} while (cin.fail() || (userInput > 213) || (userInput < -147)); // defines acceptable range of user input values

		double celsius;
		celsius = (userInput - 32) *5.0 / 9.0; //sets output formula
		cout << fixed; //enables for spesific decimal precision
		cout << setprecision(2); //sets precision value to 2 points after the decimal
		cout << "n"; //blank line
		cout << internal << showpos << setw(5) << userInput << " Degrees Fahrenheit = " << celsius << " Degrees Celsius. n" << endl << endl; //output display for result calculated with +/- symbol included

		cout << "Would you like to convert more values?" << endl << endl; //asks to continue or not
		cout << "Enter 'Y' to continue." << endl << endl; // requires user input to continue or end program
		cin >> again; //change control variable
		cout << endl; // spacing for viewing ease
	
	} // ends while loop


Include the header #include <iomanip>.

Hi dreaweiss, welcome to the forum.

I’ll outline the problems with your code:

1.) On line 4, you declare three variables. Two of them, namely ‘setprecision’ and ‘setw’ are also the names of functions found in the ‘std’ namespace. Normally, one would access these functions by using the scope-resolution operator like so: std::setprecision and std::setw. However, since you’ve elected to use using namespace std; in global scope, the compiler thinks that your function calls on lines 28 and 30 are actually attempts to treat your variables on line 4 as functions.

The way to fix this is to simply remove the offending variables on line 4, since you aren’t even using them for anything. Your fourth line of code should therefore only declare ‘again’.

2.) Technically, line 4 shouldn’t just declare ‘again’, but also define / initialize it. If you do not give ‘again’ an initial value, you’re invoking undefined behavior on line 5 when you enter the while-loop because ‘again’ contains garbage, and you’re attempting to access it. Fix this by initializing ‘again’ on line 4 (so that it may enter the while-loop).

In addition, ‘again’ shouldn’t be an int, it should be a char.

3.) There’s a discrepancy in the condition of your while-loop on line 5. What you probably meant to write was while(again == 'y' || again == 'Y'), not while(again == 'Y' || again == 'Y').

4.) The while-loop on line 5 has no body. The semi-colon (‘;’) immediately following the parentheses on line 5 is the cause of this. You will have to remove the semi-colon and add some braces (‘{‘ and ‘}’) around all of the code that should be part of the while-loop’s body.

That should be a good start. I’ve appended this basic code as a guide:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iomanip>

int main() {

	char again = 'y';
	while (again == 'y' || again == 'Y') {

		//Do things in here...

	}

	return 0;
}

Last edited on

Xismn,
Thank you
I followed all of your directions, I no longer have any errors in my code but when I run it the black boxes opens and nothing is in it. It should be asking for a Fahrenheit degree and then give it to me Celsius, and then ask if I want to convert more values. I don’t know where to go from here, with no errors showing up
This is what have now

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
#include <iostream> //allows access to iostream library
#include<iomanip>
//converting fahrenheit to celsius 
using std::cout;
using std::endl;
using std::showpos; // shows positive symbol on positive integers
#include <string> // allows for string inclusion
using namespace std;


int main()

{
char again = 'y';
{while  ( again == 'y' || again == 'Y');  //begins while loop



double userInput;

		cout << "Enter Fahrenheit Value: "; // asks for a value to convert
		do // starts the do loop
		{
			cin >> userInput ; //user input value
			cout << "n"; // blank line
			if (cin.fail() || (userInput > 213) || (userInput < -147)) // defines the range of acceptable user input values
			{
				cout << "invalid value, please try again: "; // output when unacceptable value is input
				cin.clear(); // clear 
				cin.ignore(); // so output doesn't repeat 
			}

		} while (cin.fail() || (userInput > 213) || (userInput < -147)); // defines acceptable range of user input values

		double celsius;
		celsius = (userInput - 32) *5.0 / 9.0; //sets output formula
		cout << fixed; //enables for spesific decimal precision
		cout << setprecision (2); //sets precision value to 2 points after the decimal
		cout << "n"; //blank line
		cout << internal << showpos << setw(5) << userInput << " Degrees Fahrenheit = " << celsius << " Degrees Celsius. n" << endl << endl; //output display for result calculated with +/- symbol included

		cout << "Would you like to convert more values?" << endl << endl; //asks to continue or not
		cout << "Enter 'Y' to continue." << endl << endl; // requires user input to continue or end program
		cin >> again; //change control variable
		cout << endl; // spacing for viewing ease
	
	}} // ends while loop


Last edited on

{while ( again == 'y' || again == 'Y'); //begins while loop

line 15 — two things

— Remove the semicolon at the end.
— Move the { from the beginning of the line to after the loop condition (but before the first line of the code in the loop).

1
2
3
4
while(condition)
{
   do this...
}

Wildblue,
IT WORKS !!!!!!!!
Thank you so much,
I’m crying right now… I have been working on this for a week, and just found this website yesterday!
You have no I dea how much you and Xismn have help a beginner in C++!

THANK YOU BOTH SO MUCH!!!!!!

IT runs now but It won’t compile?
It gives me and
error Id returned 1 exit status

I’ve never seen this one before

Got it I didn’t close my execution window when I ran the program !!
Thank you all !

Topic archived. No new replies allowed.

Hi I’m programming a esp8266 on Arduino but I keep getting this error, how can i solve it?

expected initializer before ‘}’ token

Arduino:1.8.12 (Mac OS X), Scheda:»NodeMCU 0.9 (ESP-12 Module), 80 MHz, Serial, 115200, 4M (3M SPIFFS)»

In file included from sketch/Accesspoints.h:7:0,
from sketch/Accesspoints.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 **buf, int len, bool sys_seq)
^
In file included from sketch/Accesspoints.cpp:1:0:
Accesspoints.h:8:1: error: expected initializer before ‘}’ token
}
^
In file included from sketch/Attack.h:7:0,
from sketch/Attack.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/Attack.h:9:0,
from sketch/Attack.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
In file included from sketch/CLI.h:8:0,
from sketch/CLI.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/CLI.h:10:0,
from sketch/CLI.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
In file included from sketch/Settings.h:7:0,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 **buf, int len, bool sys_seq)
^
In file included from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/../JsonBuffer.hpp:11:0,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/JsonParser.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/JsonBufferBase.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp:7,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.hpp:9,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.h:9,
from sketch/Settings.h:9,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/Deserialization/../Data/NonCopyable.hpp:7:1: error: expected initializer before ‘namespace’
namespace ArduinoJson {
^
In file included from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.hpp:9:0,
from /Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson.h:9,
from sketch/Settings.h:9,
from sketch/DisplayUI.h:6,
from sketch/DisplayUI.cpp:1:
/Users/raffaele/Documents/Arduino/libraries/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp:16:28: error: expected declaration before end of line
#pragma GCC diagnostic push
^
sketch/CLI.cpp: In member function ‘void CLI::load()’:
CLI.cpp:16:52: error: ‘str’ was not declared in this scope
String defaultValue = str(CLI_DEFAULT_AUTOSTART);

sketch/CLI.cpp: In member function ‘uint32_t CLI::getTime(String)’:
CLI.cpp:140:76: error: ‘str’ was not declared in this scope
else if (time.substring(time.length() — 3).equalsIgnoreCase(str(STR_MIN)) ||

sketch/CLI.cpp: In member function ‘void CLI::runCommand(String)’:
CLI.cpp:221:40: error: ‘str’ was not declared in this scope
if (list->get(0) == str(CLI_COMMENT)) {

CLI.cpp:571:47: error: ‘str’ was not declared in this scope
sprintf(s, str(CLI_RICE_OUTPUT).c_str(), i / 10);

CLI.cpp:713:41: error: ‘str’ was not declared in this scope
sprintf(s, str(CLI_SYSTEM_OUTPUT).c_str(), 81920 — system_get_free_heap_size(),

CLI.cpp:1044:60: error: ‘str’ was not declared in this scope
if (i == height) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(),

CLI.cpp:1046:69: error: ‘str’ was not declared in this scope
else if (i == height / 2) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(),

CLI.cpp:1049:60: error: ‘str’ was not declared in this scope
else if (i == 0) sprintf(s, str(CLI_DRAW_OUTPUT).c_str(), 0);

In file included from sketch/LED.h:6:0,
from sketch/LED.cpp:1:
/Users/raffaele/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/tools/sdk/include/user_interface.h:451:39: error: ‘freedom_outside_cb_t’ was not declared in this scope
int wifi_register_send_pkt_freedom_cb(freedom_outside_cb_t cb); void wifi_unregister_send_pkt_freedom__cb(void); int wifi_send_pkt_freedom(uint8 *buf, int len, bool sys_seq)
^
In file included from sketch/LED.h:8:0,
from sketch/LED.cpp:1:
language.h:6:1: error: expected initializer before ‘extern’
extern String str(const char
ptr);

^
sketch/Attack.cpp: In member function ‘void Attack::status()’:
Attack.cpp:129:25: error: ‘str’ was not declared in this scope
A_STATUS).c_str(), packetRate, deauthPkts, deauth.maxPkts, beaconPkts, beacon.maxPkts, probePkts,
^
sketch/Attack.cpp: In member function ‘bool Attack::sendPacket(uint8_t*, uint16_t, uint8_t, uint16_t)’:
Attack.cpp:412:60: error: ‘wifi_send_pkt_freedom’ was not declared in this scope
bool sent = wifi_send_pkt_freedom(packet, packetSize, 0) == 0;
^
exit status 1
expected initializer before ‘}’ token

Понравилась статья? Поделить с друзьями:
  • Error expected identifier or before string constant
  • Error expected identifier or before numeric constant
  • Error execution failed with error code 1
  • Error expected for function style cast or type construction
  • Error expected expression before token что это