Error expected initializer before int

Ошибка ожидаемый инициализатор перед int (int) int main () C++ Решение и ответ на вопрос 2485797

AleXSav95

0 / 0 / 0

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

Сообщений: 4

1

25.07.2019, 14:14. Показов 5788. Ответов 2

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


Здравствуйте

Я новичок в C++ и недавно столкнулся с такой ошибкой
при передачи массива в функцию

error: expected initializer before ‘int’

ошибка ругается на int main() и не знаю как ее исправит

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int pozishn[10]{0,1,1,1,0,0,0,0,0,0};
 
int check(int poz[])
 
int main()
{
    check(pozishn[])
}
 
int check(int poz[]){
    if(pozishn[1]==1 && pozishn[2]==1 && pozishn[3]==1){
            std::cout << "X" <<std::endl;}
    return 0;
}

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



0



Mental handicap

1245 / 623 / 171

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

Сообщений: 2,429

25.07.2019, 14:15

2

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

Решение

AleXSav95, в 8 строке забыли о ;.



0



0 / 0 / 0

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

Сообщений: 4

25.07.2019, 14:16

 [ТС]

3

опа спасибо не заметил



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

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

25.07.2019, 14:16

3

You forgot a ; in line 4 of your code dude! (In the image you posted.)

Actually there is no need of line 4: int lsearch(int [], int, int). Because in the next line you are defining the function itself. You can skip the prototype declaration if you wish.

And from next time please post proper code, not just an image. And by code I mean actual code that is causing error. Here the code in your image is different from the one which you have typed in your post!

In your typed code you are calling lsearch as lsearch(arr[], N, ITEM) [line 34]. A call should be made like this: lsearch(arr, N, ITEM).

Here is you corrected code:

#include <iostream>
using namespace std;

int lsearch(int [], int, int);

int main() {
    int N, ITEM, INDEX, ar[20];
    cout << "How many elements? (max 20): " << endl;
    cin >> N;
    cout << "Enter elements: " << endl;
    for (int i = 0; i < N; i++)
        cin >> ar[i];
    cout << "Your array is as follows: " << endl;
    for (int i = 0; i < N; i++)
        cout << ar[i] << endl;
    cout << "Enter the element to be searched for: " << endl;
    cin >> ITEM;
    INDEX = lsearch(ar, N, ITEM);
    if (INDEX == -1)
        cout << "Element not found!" << endl;
    else
        cout << "Item found at index: " << INDEX << " position: " << INDEX + 1 << endl;
    return 0;
}

int lsearch(int ar[], int N, int ITEM) {
    for (int i = 0; i < N; i++)
        if (ar[i] == ITEM)
            return i;
    return -1;
}

Sample Run:

How many elements? (max 20): 5
Enter elements: 1 2 3 4 5
Your array is as follows: 
1
2
3
4
5
Enter the element to be searched for: 4
Item found at index: 3 position: 4

This code is practically the same (I guessed this code from your image):

#include <iostream>
using namespace std;

int lsearch(int[], int, int); // Your line 4 which isn't necessary and where you missed a semi-colon!
int lsearch(int ar[], int N, int ITEM) {
    for (int i = 0; i < N; i++)
        if (ar[i] == ITEM)
            return i;
    return -1;
}

int main() {
    // same as in above code
}

You should also check out this thread on why «using namespace std» is considered a bad practice.

expected initializer before ‘int’

prog3.cpp:10:1: error: expected initializer before ‘int’
int main ()
^
this is what i get when i run this program please any help regarding this it will be much appreciated and please tell me if i made this program workable like with boolean expression if the function and prototype are well declared and performing together

/*This program ask user to input Hour, Minute and seconds and if the user
put in the valid format it runs othervise it says error. */

#include <cstdio>

bool readTime(int &hours, int &minutes, int &seconds)

int main ()
{
int h,m,s;
if(readTime(h,m,s)){
printf(«%2d:%2d:%2d» h, m, s);
return 0;
}
}

bool readTime(int &hours, int &minutes, int &seconds);
{
int hh,mm,ss;

printf(«please enter time in format 09:30:50n»);
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
}
// did they get the right format?
if (count !=3){
printf(«Invalid formatn»);
return false;
}
// is the number of hours correct?
if ((hh <0)||(hh >23)){
printf(«Invalid hour %d n», hh);
return false;
}
//is number of minutes wrong?
if ((mm <0)||(mm >0)){
printf(«Invalid Minutes %d n», mm);
return false;
}
//is number of seconds wrong?
if ((ss <0)||(ss >0)){
printf(«Invalid seconds %d n», mm);
return false;
}

}

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

bool readTime(int &hours, int &minutes, int &seconds) ; // semicolon

int main ()
{
    // ...
}

bool readTime(int &hours, int &minutes, int &seconds) //no semicolon
{
    // ...
}

@JLBorges

now this is what i get after doing your instructions

prog3.cpp: In function ‘int main()’:
prog3.cpp:14:28: error: expected ‘)’ before ‘h’
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp:14:35: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp: In function ‘bool readTime(int&, int&, int&)’:
prog3.cpp:24:8: warning: unused variable ‘count’ [-Wunused-variable]
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
^
prog3.cpp:25:4: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
prog3.cpp: At global scope:
prog3.cpp:27:4: error: expected unqualified-id before ‘if’
if (count !=3){
^
prog3.cpp:32:4: error: expected unqualified-id before ‘if’
if ((hh <0)||(hh >23)){
^
prog3.cpp:37:4: error: expected unqualified-id before ‘if’
if ((mm <0)||(mm >0)){
^
prog3.cpp:42:4: error: expected unqualified-id before ‘if’
if ((ss <0)||(ss >0)){
^
prog3.cpp:47:1: error: expected declaration before ‘}’ token
}
^

You have extra braces.

You will find it extremely helpful to
1. Indent your code consistently. Use an editor which does this for you.
2. Type the closing brace at the same type you type the opening brace. Use an editor which does this for you.

Here is a «fixed» version. (there’s still some issues, but it will compile with warnings.)

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
#include <cstdio>

bool readTime(int &hours, int &minutes, int &seconds);

int main ()
{
  int h,m,s;
  if(readTime(h,m,s)){
    printf("%2d:%2d:%2d" h, m, s);
    return 0;
  }
}

bool readTime(int &hours, int &minutes, int &seconds)
{
  int hh,mm,ss;

  printf("please enter time in format 09:30:50n");
  int count = scanf("%2d:%2d:%2d", &hh, &mm, &ss);

  // did they get the right format?
  if (count !=3){
    printf("Invalid formatn");
    return false;
  }
  // is the number of hours correct?
  if ((hh <0)||(hh >23)){
    printf("Invalid hour %d n", hh);
    return false;
  }
  //is number of minutes wrong?
  if ((mm <0)||(mm >0)){
    printf("Invalid Minutes %d n", mm);
    return false;
  }
  //is number of seconds wrong?
  if ((ss <0)||(ss >0)){ 
    printf("Invalid seconds %d n", mm);
    return false;
  }
}

@mobzzi

i run your program but then i see this issue it will be helpful if i get perfectly running program so that i know for my upcoming exam how to make this type of program run. I am currently preparing for my exam. hope to see some help from you guys out there

In function ‘int main()’:
9:26: error: expected ‘)’ before ‘h’
9:33: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
In function ‘bool readTime(int&, int&, int&)’:
41:1: warning: control reaches end of non-void function [-Wreturn-type]

This line :
printf("%2d:%2d:%2d" h, m, s);

Should be :
printf("%2d:%2d:%2d", h, m, s); // An extra comma (,)

Last edited on

@sakurasouBusters

thank you for the help but why am i facing problem like this?

progs3.cpp:41:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^

Notice that the compiler provides you with the location of any errors that it encounters.

1
2
In function 'int main()':
9:26: error: expected ')' before 'h'

Line 9, column 26 — usually there’s a filename, too. There’s a missing comma (I missed it, apologies.)

If the problem is a syntax error, the compiler will report the error no earlier than it appears. Look at the location of the first error and then look backwards towards the beginning of the file until you find it.

@mbozzi

thank you for the help its so much appreciated and helpful for my upcoming exam and future programming errors. but can you help me with my issue on line 41?

Topic archived. No new replies allowed.

Here’s the whole code:

/
A basic example of Win32 programmiwng in C.

This source code is in the PUBLIC DOMAIN and has NO WARRANTY.

Colin Peters colin@bird.fu.is.saga-u.ac.jp
*/

include <windows.h>

include <string.h>

include <iostream>

/
This is the window function for the main window. Whenever a message is
dispatched using DispatchMessage (or sent with SendMessage) this function
gets called with the contents of the message.
/
LRESULT CALLBACK
MainWndProc (HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
/
The window handle for the «Click Me» button. /
static HWND hwndButton = 0;
static int cx, cy;/
Height and width of our button. */

HDC hdc;/ A device context used for drawing /
PAINTSTRUCT ps;/ Also used during window drawing /
RECT rc;/ A rectangle used during drawing /
/
Perform processing based on what kind of message we got.
/
switch (nMsg)
{
case WM_CREATE:
{
/
The window is being created. Create our button
window now. /
TEXTMETRIC tm;

/ First we use the system fixed font size to choose
a nice button size. */
hdc = GetDC (hwnd);
SelectObject (hdc, GetStockObject (SYSTEM_FIXED_FONT));
GetTextMetrics (hdc, &tm);
cx = tm.tmAveCharWidth * 30;
cy = (tm.tmHeight + tm.tmExternalLeading) * 2;
ReleaseDC (hwnd, hdc);

/ Now create the button /
hwndButton = CreateWindow (
«button»,/ Builtin button class /
«Click Here»,
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
0, 0, cx, cy,
hwnd,/ Parent is this window. /
(HMENU) 1,/ Control ID: 1 /
((LPCREATESTRUCT) lParam)->hInstance,
NULL
);

return 0;
break;
}

case WM_DESTROY:
/ The window is being destroyed, close the application
(the child button gets destroyed automatically). */
PostQuitMessage (0);
return 0;
break;

case WM_PAINT:
/ The window needs to be painted (redrawn). /
hdc = BeginPaint (hwnd, &ps);
GetClientRect (hwnd, &rc);

/ Draw «Hello, World» in the middle of the upper
half of the window. */
rc.bottom = rc.bottom / 2;
DrawText (hdc, «Hello, World!», -1, &rc,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);

EndPaint (hwnd, &ps);
return 0;
break;

case WM_SIZE:
/ The window size is changing. If the button exists
then place it in the center of the bottom half of
the window. /
if (hwndButton &&
(wParam == SIZEFULLSCREEN ||
wParam == SIZENORMAL)
)
{
rc.left = (LOWORD(lParam) — cx) / 2;
rc.top = HIWORD(lParam) * 3 / 4 — cy / 2;
MoveWindow (
hwndButton,
rc.left, rc.top, cx, cy, TRUE);
}
break;

case WM_COMMAND:
/ Check the control ID, notification code and
control handle to see if this is a button click
message from our child button. /
if (LOWORD(wParam) == 1 &&
HIWORD(wParam) == BN_CLICKED &&
(HWND) lParam == hwndButton)
{
/ Our button was clicked. Close the window. /
DestroyWindow (hwnd);
}
return 0;
break;
}

/ If we don’t handle a message completely we hand it to the system
provided default window function. */
return DefWindowProc (hwnd, nMsg, wParam, lParam);
}

int STDCALL

WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
HWND hwndMain;/ Handle for the main window. /
MSG msg;/ A Win32 message structure. /
WNDCLASSEX wndclass;/ A window class structure. /
charszMainWndClass = «WinTestWin»;
/
The name of the main window class */

/
First we create a window class for our main window.
*/

/ Initialize the entire structure to zero. /
memset (&wndclass, 0, sizeof(WNDCLASSEX));

/ This class is called WinTestWin /
wndclass.lpszClassName = szMainWndClass;

/ cbSize gives the size of the structure for extensibility. /
wndclass.cbSize = sizeof(WNDCLASSEX);

/ All windows of this class redraw when resized. /
wndclass.style = CS_HREDRAW | CS_VREDRAW;

/ All windows of this class use the MainWndProc window function. /
wndclass.lpfnWndProc = MainWndProc;

/ This class is used with the current program instance. /
wndclass.hInstance = hInst;

/ Use standard application icon and arrow cursor provided by the OS /
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);

/ Color the background white /
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);

/
Now register the window class for use.
*/
RegisterClassEx (&wndclass);

/
Create our main window using that window class.
/
hwndMain = CreateWindow (
szMainWndClass,/
Class name /
«Hello»,/
Caption /
WS_OVERLAPPEDWINDOW,/
Style /
CW_USEDEFAULT,/
Initial x (use default) /
CW_USEDEFAULT,/
Initial y (use default) /
CW_USEDEFAULT,/
Initial x size (use default) /
CW_USEDEFAULT,/
Initial y size (use default) /
NULL,/
No parent window /
NULL,/
No menu /
hInst,/
This program instance /
NULL/
Creation parameters */
);

/
Display the window which we just created (using the nShow
passed by the OS, which allows for start minimized and that
sort of thing).
*/
ShowWindow (hwndMain, nShow);
UpdateWindow (hwndMain);

/
The main message loop. All messages being sent to the windows
of the application (or at least the primary thread) are retrieved
by the GetMessage call, then translated (mainly for keyboard
messages) and dispatched to the appropriate window procedure.
This is the simplest kind of message loop. More complex loops
are required for idle processing or handling modeless dialog
boxes. When one of the windows calls PostQuitMessage GetMessage
will return zero and the wParam of the message will be filled
with the argument to PostQuitMessage. The loop will end and
the application will close.
/
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}

Содержание

  1. Error expected initializer before cin
  2. Error expected initializer before cin
  3. Error expected initializer before cin
  4. Error expected initializer before cin
  5. Error expected initializer before cin

Error expected initializer before cin

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.

Источник

Error expected initializer before cin

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

You do have something essential missing, the braces around the body of the function.
See: http://www.cplusplus.com/doc/tutorial/program_structure/

Once you have followed that advice you will get a different error: What is the «again»?

PS. Please edit your post to use code tags.
See: http://www.cplusplus.com/articles/jEywvCM9/
Pay attention to indentation too. It can help reading your code.

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.

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

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:

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

Источник

Error expected initializer before cin

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

You do have something essential missing, the braces around the body of the function.
See: http://www.cplusplus.com/doc/tutorial/program_structure/

Once you have followed that advice you will get a different error: What is the «again»?

PS. Please edit your post to use code tags.
See: http://www.cplusplus.com/articles/jEywvCM9/
Pay attention to indentation too. It can help reading your code.

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.

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

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:

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

Источник

Error expected initializer before cin

I Keep getting this error message, and i’m sure it has something to do with how I am attempting to call my functions. I have been at this for hours, what am I doing wrong?

error: expected initializer before ‘double’
double tsav(int tstotal,int tsgradecounter, int grade)

using namespace std;

double qzav(int qztotal,int qzgradecounter, int grade)
double tsav(int tstotal,int tsgradecounter, int grade)

double hwav(int hwtotal,int hwgradecounter, int grade)

int option; //option for menu

string firstname;
double qzaverage= qzav(qztotal,qzgradecounter,grade);
double tsaverage= tsav(tstotal,tsgradecounter,grade);
double hwaverage= hwav(hwtotal,hwgradecounter,grade);

cout > option; //print option

cout>> «Quiz»>> endl;
cin >»Test»>> endl;
cin >»Homework»>> endl;
cin > «Quiz averager»;
cout > grade;

qztotal= qztotal + grade; //total quiz grade

qzgradecounter= qzgradecounter + 1;

if (qzgradecounter !=0)

qzaverage= static_cast (qztotal)/ qzgradecounter;

tstotal= tstotal + grade;

tsgradecounter= tsgradecounter + 1;

if (tsgradecounter !=0)

tsaverage= static_cast (tstotal)/ tsgradecounter;

hwtotal= hwtotal + grade;

hwgradecounter= hwgradecounter + 1;

if (hwgradecounter !=0)

hwaverage= static_cast (hwtotal)/ hwgradecounter;

Источник

Error expected initializer before cin

prog3.cpp:10:1: error: expected initializer before ‘int’
int main ()
^
this is what i get when i run this program please any help regarding this it will be much appreciated and please tell me if i made this program workable like with boolean expression if the function and prototype are well declared and performing together

/*This program ask user to input Hour, Minute and seconds and if the user
put in the valid format it runs othervise it says error. */

bool readTime(int &hours, int &minutes, int &seconds)

int main ()
<
int h,m,s;
if(readTime(h,m,s)) <
printf(«%2d:%2d:%2d» h, m, s);
return 0;
>
>

printf(«please enter time in format 09:30:50n»);
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
>
// did they get the right format?
if (count !=3) <
printf(«Invalid formatn»);
return false;
>
// is the number of hours correct?
if ((hh 23)) <
printf(«Invalid hour %d n», hh);
return false;
>
//is number of minutes wrong?
if ((mm 0)) <
printf(«Invalid Minutes %d n», mm);
return false;
>
//is number of seconds wrong?
if ((ss 0)) <
printf(«Invalid seconds %d n», mm);
return false;
>

now this is what i get after doing your instructions

prog3.cpp: In function ‘int main()’:
prog3.cpp:14:28: error: expected ‘)’ before ‘h’
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp:14:35: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp: In function ‘bool readTime(int&, int&, int&)’:
prog3.cpp:24:8: warning: unused variable ‘count’ [-Wunused-variable]
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
^
prog3.cpp:25:4: warning: no return statement in function returning non-void [-Wreturn-type]
>
^
prog3.cpp: At global scope:
prog3.cpp:27:4: error: expected unqualified-id before ‘if’
if (count !=3) <
^
prog3.cpp:32:4: error: expected unqualified-id before ‘if’
if ((hh 23)) <
^
prog3.cpp:37:4: error: expected unqualified-id before ‘if’
if ((mm 0)) <
^
prog3.cpp:42:4: error: expected unqualified-id before ‘if’
if ((ss 0)) <
^
prog3.cpp:47:1: error: expected declaration before ‘>’ token
>
^

You have extra braces.

You will find it extremely helpful to
1. Indent your code consistently. Use an editor which does this for you.
2. Type the closing brace at the same type you type the opening brace. Use an editor which does this for you.

Here is a «fixed» version. (there’s still some issues, but it will compile with warnings.)

i run your program but then i see this issue it will be helpful if i get perfectly running program so that i know for my upcoming exam how to make this type of program run. I am currently preparing for my exam. hope to see some help from you guys out there

In function ‘int main()’:
9:26: error: expected ‘)’ before ‘h’
9:33: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
In function ‘bool readTime(int&, int&, int&)’:
41:1: warning: control reaches end of non-void function [-Wreturn-type]

This line :
printf( «%2d:%2d:%2d» h, m, s);

Should be :
printf( «%2d:%2d:%2d» , h, m, s); // An extra comma (,)

thank you for the help but why am i facing problem like this?

progs3.cpp:41:1: warning: control reaches end of non-void function [-Wreturn-type]
>
^

Notice that the compiler provides you with the location of any errors that it encounters.

Line 9, column 26 — usually there’s a filename, too. There’s a missing comma (I missed it, apologies.)

If the problem is a syntax error, the compiler will report the error no earlier than it appears. Look at the location of the first error and then look backwards towards the beginning of the file until you find it.

thank you for the help its so much appreciated and helpful for my upcoming exam and future programming errors. but can you help me with my issue on line 41?

Источник

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before cout
  • Error expected initializer before class
  • Error expected initializer before cin
  • Error expected initializer before char
  • Error expected indentation of 6 spaces but found 4 indent