Error expected initializer before std

anisha@linux-trra:~> make g++ -c -m64 -pipe -I/usr/lib64/R/include -I/usr/lib64/R/library/Rcpp/include -I/usr/lib64/R/library/RInside/include -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -
anisha@linux-trra:~> make
g++ -c -m64 -pipe -I/usr/lib64/R/include -I/usr/lib64/R/library/Rcpp/include -I/usr/lib64/R/library/RInside/include -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/home/anisha/qtsdk-2010.05/qt/mkspecs/linux-g++-64 -I. -I/home/anisha/qtsdk-2010.05/qt/include/QtCore -I/home/anisha/qtsdk-2010.05/qt/include/QtGui -I/home/anisha/qtsdk-2010.05/qt/include -I. -o zoomCornerPanDatabaseParser.o zoomCornerPanDatabaseParser.cpp
In file included from zoomCornerPanDatabaseParser.h:9:0,
                 from zoomCornerPanDatabaseParser.cpp:1:
*******************boundaryLineEquation.cpp:6:1: error: expected initializer before ‘std’
make: *** [zoomCornerPanDatabaseParser.o] Error 1

The .cpp:

#include <math.h>
#include <string>
#include "boundaryLineEquation.h"

/// This function will return the direction of the new point as w.r.t to the given rectangle.
********************std :: string findPanDirection (float x1, float y1, float x2, float y2, float newX, float newY)
{
    if (x1 > x2)
    {
        float temp = x1;
        x1 =x2;
        x2 = temp;
    }

    if (y2 > y1)
    {
        float temp = y2;
        y2 = y1;
        y1 = temp;
    }

    if (newX < x1 )
    {

The .h:

#include <iostream>

#ifndef RLINE
#define RLINE

std :: string findPanDirection (float x1, float y1, 
                        float x2, float y2, 
                        float newX, float newY);

bool returnDistance (float centerPointLng, float centerPointLat, 
                float newCenterPointLng, float newCenterPointLat)

#endif

Аманта

0 / 0 / 0

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

Сообщений: 6

1

14.02.2019, 21:14. Показов 21254. Ответов 3

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


Подскажите, пожалуйста, я только начинаю изучать с++. в программе:

C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
Int main()
Int s
{
cin >> s;
cout << s;
cin get();
return 0;
}

Возникает ошибка: expected initializer before ‘int’
int s
^~~
Как её исправить? Все варианты уже перепробовала. Заранее спасибо.

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



0



Байт

Диссидент

Эксперт C

27209 / 16962 / 3749

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

Сообщений: 38,147

14.02.2019, 21:18

2

C++
1
2
3
4
5
6
7
8
9
10
include <iostream>
using namespace std;
int main()
{
int s;
cin >> s;
cout << s;
cin get();
return 0;
}

В Си(++) регистр букв имеет значение. int — Int — вещи разные.
Ну и синтаксис…



1



324 / 217 / 105

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

Сообщений: 944

14.02.2019, 21:18

3

Int что за тип? int



0



0 / 0 / 0

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

Сообщений: 6

16.02.2019, 09:20

 [ТС]

4

Спасибо огромное! Вчё получилось!



0



  • Forum
  • Beginners
  • expected initializer before «std»

expected initializer before «std»

#include <iostream>

int main()

{

int n,a,b,c,s

std::cout<<«n=»; std::cin>>n;

a=n/100;

b=n/10%10;

c=n%10;

s=a+b+c;

std::cout<<«The digits sum is:»<<s;

return 0;

}

What did I do wrong here? It tells me that the «std::cout<<«n=»; std::cin>>n;» line is wrong and says «expected initializer before «std»».Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int n,a,b,c,s; //was missing a semicolon here

    std::cout << "n = ";
    std::cin >> n;

    a = n / 100;
    b = n / 10 % 10;
    c = n % 10;
    s = a + b + c;

    std::cout << "nThe digits sum is: " << s;

    return 0;
}

Last edited on

int n,a,b,c,s has no semi-colon.

PLEASE learn to use code tags, it makes it easier to read your code.

You can edit your post and add the tags.

http://www.cplusplus.com/articles/jEywvCM9/

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

int main()

{



   int n, a, b, c, s

   std::cout << "n="; std::cin >> n;

   a = n / 100;

   b = n / 10 % 10;

   c = n % 10;

   s = a + b + c;

   std::cout << "The digits sum is:" << s;

   return 0;

}

Topic archived. No new replies allowed.

I can’t figure out whats wrong with my code. When I compile it, the only error I get is «expected initializer before ‘int’ in line 9. I’m still pretty new and uneducated in this, so I’m not too sure what the heck is going on. Any help is appreciated.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

    int m, d, year, choice, i, passed, orig, yy; 
    char more = 'y';
    int  days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int leap(int x)
int main()
{ 
{
  while (more == 'y' || more == 'Y') {
  	printf ("ntThis program will find days passed or date in the year");
  	printf ("nttt1)  Input date (mm/dd/yyyy) to find dates passed");
  	printf ("nttt2)  Input passed days to find date in the year");
  	printf ("nnttYour choice (1/2): ");
  	scanf  ("%d",&choice);	}
  }
  		char letter (int c)
  		{
  		if (c == 1);{
  	
    int daysInMonth = 0;
    int daysPassed = 0;
    int leapyear = 0;     
    printf("nnnttPlease input date (mm-dd-yyyy): ");
    scanf ("%d/%d/%d", &m, &d, &year);
    if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            leapyear=1;  
      switch(m-1)  {
        case 12:
          daysInMonth=31;
          daysPassed += daysInMonth;             
        case 11:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 10:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 9:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 8:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 7:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 6:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 5:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 4:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 3:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 2:
          if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
            leapyear=1;
            daysInMonth=29;
            daysPassed += daysInMonth;
          }  
          else{
            daysInMonth=28;
            daysPassed += daysInMonth;
          }    
        case 1:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 0:  
          if(m <=7 && m % 2 != 0 && d <= 31 || m >= 8 && m % 2 == 0 && d <= 31)   
            daysPassed += d;
          else 
            if(m == 2 && leapyear == 1 && d <= 29 || m == 2 && leapyear == 0 && d <= 28)
              daysPassed += d;
            else
             if(m <=6 && m % 2 == 0 && d <= 30 && m != 2|| m >= 9 && m % 2 != 0 && d <= 30)
               daysPassed += d;
             else{
               printf("ntttYour input mm/dd/yyyy is wrong!");     
               break;        
             }           
        printf("nntttThere are %d days past in the year", daysPassed);          
        break;   
        default: printf("ntttYour input mm/dd/yyyy is wrong!");
    	}
    }
	 	if (c == 2)
{
	{
    if (x % 4 == 0 && x % 100 != 0 || x % 400 == 0)
        return 1;
    else
        return 0;
}


    
    do   {
        printf ("nttInput days: ");
        scanf  ("%d", &passed);
        printf ("ntt      Year: ");
        scanf  ("%d", &yy);
        
        if (leap(yy))
            days[1] = 29;
        else
            days[1] = 28;
        
        orig = passed;
        
        for (i = 0; passed > 0; i++)
            passed = passed - days [i];
        passed = passed + days [i - 1]; 
        
        printf ("nttThe date is %d-%d-%d",
                                            i, passed, yy, orig);
		}
        printf ("nnttDo more (Y/N)? ");
        scanf  ("%s", &more);		}
       }while (more == 'y'  ||  more == 'Y');
   
  return 0;        
}

Table of Contents

Common G++ Errors

Summary

This is a guide to help you CS35ers make sense of g++ and its often cryptic error messages.

If you discover an error not listed here feel free to edit this wiki,
or send your error along with source code and an explanation to me — grawson1@swarthmore.edu

Weird Errors

If you are getting strange compiler errors when your syntax looks fine, it might be a good idea to check that your Makefile is up to date
and that you are including the proper .h files. Sometimes a missing } or ; or ) will yield some scary errors as well.
Lastly, save all files that you might have changed before compiling.

Bad Code Sample

What’s wrong with the following code? (Hint: there are two errors)

#include<iostream>
using namespace std;
 
int main(){
 
  int foo;
 
  for(int i = 0, i<100, i++) {
    foo++;
    cout << foo << endl;
  }
  return 0;
}

When compiled this yields:

junk.cpp:9: error: expected initializer before '<' token

junk.cpp:13: error: expected primary-expression before 'return

junk.cpp:13: error: expected `;' before 'return

junk.cpp:13: error: expected primary-expression before 'return

junk.cpp:13: error: expected `)' before 'return

First, the parameters of the for loop need to be separated by semicolons, not commas.

for(int i = 0; i<100; i++) {
    foo++;
    cout << foo << endl;
  }

Now look at this sample output of the corrected code:

-1208637327

-1208637326

-1208637325

-1208637324

-1208637323

-1208637322

Why the weird values? Because we never initialized foo before incrementing it.

 int foo = 0;

‘cout’ was not declared in this scope

Two things to check here:

(1) Did you add

 #include<iostream> 

to your list of headers?
(2) Did you add

 using namespace std; 

after your #includes?

‘printf’ was not declared in this scope

Add

 #include<cstdio> 

to your list of headers. Note if you are coming from C programming, adding
#include<cstdio> is preferred in C++ over #include <stdio.h>.

Cannot Pass Objects of non-POD Type

junk.cpp:8: warning: cannot pass objects of non-POD type 'struct std::string' through '…'; call will abort at runtime

junk.cpp:8: warning: format '%s' expects type 'char*', but argument 2 has type 'int

What this usually means is that you forgot to append .c_str() to the name of your string variable when using printf.

This error occurred when trying to compile the following code:

int main(){
 
  string foo = "dog";
  printf("This animal is a %s.n",foo);
  return 0;
}

Simply appending to .c_str() to “foo” will fix this:

printf("This animal is a %s.n",foo.c_str());

The reason you got this error is because printf is a C function and C handles strings differently than C++

Invalid Use of Member

junk.cpp:8: error: invalid use of member (did you forget the '&' ?)

What this usually means is that you forget to add () to the end of a function call.

Ironically, every time I see this it is never because I forgot the ‘&’.
This error occurred when trying to compile the following code:

int main(){
 
  string foo = "dog";
  printf("This animal is a %s.n",foo.c_str);
 
  return 0;
}

Simply adding the open and close parentheses () will take care of this for you:

printf("This animal is a %s.n",foo.c_str());

Request for Member ‘Foo’ in ‘Bar’, which is of non-class type ‘X’

trycredit.cpp:86: error: request for member 'print' in 'card', which is of non-class type 'CreditCard*

What this usually means is that you are using a ‘.’ between the class pointer and the function you are trying to call.
Here is an example from the CreditCard lab:

void useCard(CreditCard *card, int method) {
  //Used to access the methods of the class
 
  if (method==1) {
    card.print();
  }

Since card is a CreditCard* we need → rather than . Fixed:

  if (method==1) {
    card->print();
  }

Undefined Reference to V Table

This error usually means you need to add a destructor to your myClass.cpp/myClass.inl code.
If you don’t want to implement a real destructor at this point, you can write something like this:

myClass::~myClass(){}

So long as the destructor exists, you should now be able to compile fine. Of course,
implement a real destructor at a later point.

Содержание

  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?

Источник

Я получаю эту ошибку во время компиляции (g ++ 4.4.6):

main.cpp: In function ‘int main()’:
main.cpp:27: error: expected initializer before ‘:’ token
main.cpp:33: error: expected primary-expression before ‘for’
main.cpp:33: error: expected ‘;’ before ‘for’
main.cpp:33: error: expected primary-expression before ‘for’
main.cpp:33: error: expected ‘)’ before ‘for’
main.cpp:33: error: expected initializer before ‘:’ token
main.cpp:36: error: could not convert ‘((list != 0u) ? (list->SortedList::~SortedList(), operator delete(((void*)list))) : 0)’ to ‘bool’
main.cpp:37: error: expected primary-expression before ‘return’
main.cpp:37: error: expected ‘)’ before ‘return’

Мой код выглядит следующим образом:

#include <iostream>
#include "Student.h"
#include "SortedList.h"

using namespace std;

int main() {
    SortedList *list = new SortedList();

    Student create[100];
    int num = 100000;

    for (Student &x : create) { // <--Line 27
        x = new Student(num);
        num += 10;
    }

    for (Student &x : create)
    list->insert(&x);

    delete list;
    return 0;
}

Любой, кто, возможно, знает источник ошибки, будет большим подспорьем. Кроме того, Student и SortedList — это объекты, объявленные в их файлах .h.

СОДЕРЖАНИЕ ►

  • Произошла ошибка при загрузке скетча в Ардуино
    • programmer is not responding
    • a function-definition is not allowed arduino ошибка
    • expected initializer before ‘}’ token arduino ошибка
    • ‘что-то’ was not declared in this scope arduino ошибка
    • No such file or directory arduino ошибка
  • Compilation error: Missing FQBN (Fully Qualified Board Name)

Ошибки компиляции Arduino IDE возникают при проверке или загрузке скетча в плату, если код программы содержит ошибки, компилятор не может найти библиотеки или переменные. На самом деле, сообщение об ошибке при загрузке скетча связано с невнимательностью самого программиста. Рассмотрим в этой статье все возможные ошибки компиляции для платы Ардуино UNO R3, NANO, MEGA и пути их решения.

Произошла ошибка при загрузке скетча Ардуино

Самые простые ошибки возникают у новичков, кто только начинает разбираться с языком программирования Ардуино и делает первые попытки загрузить скетч. Если вы не нашли решение своей проблемы в статье, то напишите свой вопрос в комментариях к этой записи и мы поможем решить вашу проблему с загрузкой (бесплатно!).

avrdude: stk500_recv(): programmer is not responding

Что делать в этом случае? Первым делом обратите внимание какую плату вы используете и к какому порту она подключена (смотри на скриншоте в правом нижнем углу). Необходимо сообщить Arduino IDE, какая плата используется и к какому порту она подключена. Если вы загружаете скетч в Ардуино Nano V3, но при этом в настройках указана плата Uno или Mega 2560, то вы увидите ошибку, как на скриншоте ниже.

Ошибка: programmer is not responding

Ошибка Ардуино: programmer is not responding

Такая же ошибка будет возникать, если вы не укажите порт к которому подключена плата (это может быть любой COM-порт, кроме COM1). В обоих случаях вы получите сообщение — плата не отвечает (programmer is not responding). Для исправления ошибки надо на панели инструментов Arduino IDE в меню «Сервис» выбрать нужную плату и там же, через «Сервис» → «Последовательный порт» выбрать порт «COM7».

a function-definition is not allowed here before ‘{‘ token

Это значит, что в скетче вы забыли где-то закрыть фигурную скобку. Синтаксические ошибки IDE тоже распространены и связаны они просто с невнимательностью. Такие проблемы легко решаются, так как Arduino IDE даст вам подсказку, стараясь отметить номер строки, где обнаружена ошибка. На скриншоте видно, что строка с ошибкой подсвечена, а в нижнем левом углу приложения указан номер строки.

Ошибка: a function-definition is not allowed

Ошибка: a function-definition is not allowed here before ‘{‘ token

expected initializer before ‘}’ token   expected ‘;’ before ‘}’ token

Сообщение expected initializer before ‘}’ token говорит о том, что вы, наоборот где-то забыли открыть фигурную скобку. Arduino IDE даст вам подсказку, но если скетч довольно большой, то вам придется набраться терпения, чтобы найти неточность в коде. Ошибка при компиляции программы: expected ‘;’ before ‘}’ token говорит о том, что вы забыли поставить точку с запятой в конце командной строки.

‘что-то’ was not declared in this scope

Что за ошибка? Arduino IDE обнаружила в скетче слова, не являющиеся служебными или не были объявлены, как переменные. Например, вы забыли продекларировать переменную или задали переменную ‘DATA’, а затем по невнимательности используете ‘DAT’, которая не была продекларирована. Ошибка was not declared in this scope возникает при появлении в скетче случайных или лишних символов.

Ошибка Ардуино: was not declared in this scope

Ошибка Ардуино: was not declared in this scope

Например, на скриншоте выделено, что программист забыл продекларировать переменную ‘x’, а также неправильно написал функцию ‘analogRead’. Такая ошибка может возникнуть, если вы забудете поставить комментарий, написали функцию с ошибкой и т.д. Все ошибки также будут подсвечены, а при нескольких ошибках в скетче, сначала будет предложено исправить первую ошибку, расположенную выше.

exit status 1 ошибка компиляции для платы Arduino

Данная ошибка возникает, если вы подключаете в скетче библиотеку, которую не установили в папку libraries. Например, не установлена библиотека ИК приемника Ардуино: fatal error: IRremote.h: No such file or directory. Как исправить ошибку? Скачайте нужную библиотеку и распакуйте архив в папку C:Program FilesArduinolibraries. Если библиотека установлена, то попробуйте скачать и заменить библиотеку на новую.

exit status 1 Ошибка компиляции для Arduino Nano

exit status 1 Ошибка компиляции для платы Arduino Nano

Довольно часто у новичков выходит exit status 1 ошибка компиляции для платы arduino uno /genuino uno. Причин данного сообщения при загрузке скетча в плату Arduino Mega или Uno может быть огромное множество. Но все их легко исправить, достаточно внимательно перепроверить код программы. Если в этом обзоре вы не нашли решение своей проблемы, то напишите свой вопрос в комментариях к этой статье.

missing fqbn (fully qualified board name)

Ошибка возникает, если не была выбрана плата. Обратите внимание, что тип платы необходимо выбрать, даже если вы не загружаете, а, например, делаете компиляцию скетча. В Arduino IDE 2 вы можете использовать меню выбора:
— список плат, которые подключены и были идентифицированы Arduino IDE.
— или выбрать плату и порт вручную, без подключения микроконтроллера.

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before progmem
  • Error expected initializer before numeric constant
  • Error expected initializer before int
  • Error expected initializer before float
  • Error expected initializer before double