Error expected initializer before using

im new here ,and new at proggraming in general . whem im trying to run this code: #include #include #include "main.h" using namespace std; int main() { short arr_...

im new here ,and new at proggraming in general .
whem im trying to run this code:

#include<fstream>
#include <iostream>
#include "main.h"
using namespace std;
int main()
{
 short arr_size ()
float temp;
point point_arr[99];
ifstream my_file   ("points.txt");
while(!my_file.eof())
{
    my_file>>temp ;
    point_arr[arr_size].set_x(temp);
    my_file>>temp ;
    point_arr[arr_size].set_y(temp);
    arr_size++;
}
arr_size--;
my_file.close();
ex_point(point_array,arr_size);
cout<<"the middle point is:("<<mid_p(point_array,arr_size).get_x()<<","<<mid_p(point_array,arr_size).get_y()<<")n";
return 0;
}

im getting this error : «error «expected initializer before ‘using'» c++»
this is the first time i get this error . it may be somthing wrong with «main.h» ?
this is «main.h » :

    #ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include<iostream>
class point
{
    float x ,y ;
public :
    point(float a,float b){x=a;y=b;}
    point(){};
    void set_x(float a){x=a;};
    void set_y(float b){x=b;};
    const float get_x(){return x; };
    const float get_y(){return y; };
    const void show();
    const float pitagoras();
};
const point mid_p(point[],float);
const void ex_point(point[],float)



#endif // MAIN_H_INCLUDED

thank you !
ivory

Rumsky

0 / 0 / 0

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

Сообщений: 8

1

01.05.2013, 17:56. Показов 1799. Ответов 2

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


Что не так?
Search_time_Uvx.cpp:6:1: error: expected initializer before ‘using’

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <math.h>
 
#include "Wheres_Your_Head_At.h"
 
using namespace std;
 
void Search_time_Uvx()
 
{
 
    float  vrem1,vrem2,Uvx;
   printf("Search time ... <Enter value of Uvx>");
   scanf("%f", &Uvx);
   
    
    vrem1=sqrt(log(10/Uvx))/1.5;
    vrem2=-(sqrt(log(10/Uvx))/1.5);
   
    printf("vrem1=%6.4f  vrem2=%6.4fn", vrem1,vrem2);
 
}

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



0



5225 / 3197 / 362

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

Сообщений: 8,101

Записей в блоге: 2

01.05.2013, 18:02

2

проблема в файле Wheres_Your_Head_At.h.



1



0 / 0 / 0

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

Сообщений: 8

01.05.2013, 18:05

 [ТС]

3

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

проблема в файле Wheres_Your_Head_At.h.

Блин) Я слепой=Р «;» забыл)



0



Содержание

  1. Error expected initializer before using
  2. Error expected initializer before using
  3. Error expected initializer before using
  4. Error expected initializer before using

Error expected initializer before using

I have not a lot of experience with C++. So far I did everything in one file. Now I tried to use 2 source files and 1 header.
I get the message that an initializer is expected.

This is the code of the mein source file (where the error is reported)

#include
#include
#include
#include «subs.h»

using namespace std;

int main()
<
int N(10000); //number of steps for the randomwalk
int N2(1000); //number of randomwalks
double steplength(1); //length of one step
double *R;
R= new double[N2];
//initial seed
int seed (11324);

#include
#include
#include

using namespace std;

double randomwalk(int seed, int N, double steplength) <
//random number generator
unsigned int c(16807);
unsigned int p(21474837);
unsigned int *r;
double *randomnumb;
r= new unsigned int[N+1];
randomnumb=new double [N];
r[0]=seed;
randomnumb[0]=r[0];
randomnumb[0]=randomnumb[0]/p;
//generate random numbers
for(int i=1;i

Sorry, the last line «and the header» should be above:

#ifndef SUBS_H_INCLUDED
#define SUBS_H_INCLUDED

int N(10000); //number of steps for the randomwalk
int N2(1000); //number of randomwalks

These values, Right?

What is with these values?

The error message is: line 6 error: expected initializer before using

There is some problem with an initializer, but I don’t know what this means.

correct me if I’m wrong but you have 3 files

If this is what you mean your on the right track, but you need to understand how compiling works.
To put it in a simple way, the compiler will compile every cpp file separately first, doing a #include «something.h» will tell the compiler that some thing you call will be found in a other file (in this case something.h. But at this point the compiler has no clue where the code is only what will be in it. After this the linker will combine all these files to one binary. In your case the linker can’t find where the actual code for subs.h is (sins header and source files don’t need to have the same name or even be in the same location) This is why a source file needs to include it’s own header file to let the linker know what header file is linked to what source file. So you only need to add #include «subs.h» to the top of your subs.cpp file:

And since you are using header safeguards the actual source will only be inserted ones (upon the first include) in the final binary.

(In a actual compiler and more advanced stuff it’s a bit more complicated then this, and the compiler/linker does many more things. But that’s stuff you don’t touch unless you know what you are doing.)

Ok, I added #include «subs.h» into my randomwalk.cpp file. I still get an error «expected initializer before double». It is in the randomwalk.cpp file. (6. Line)

To your first question, yes I have 3 files, only that the file subs.cpp is called randomwalk.cpp .

This is what I compiled on my computer and it worked fine:
If you still get a error with this, it’s not in the code.

What is the command you use to compile and link?

Источник

Error expected initializer before using

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 using

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 using

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

Источник

Initializer

I have not a lot of experience with C++. So far I did everything in one file. Now I tried to use 2 source files and 1 header.
I get the message that an initializer is expected.

This is the code of the mein source file (where the error is reported)

#include <iostream>
#include <fstream>
#include <cmath>
#include «subs.h»

using namespace std;

int main()
{
int N(10000); //number of steps for the randomwalk
int N2(1000); //number of randomwalks
double steplength(1); //length of one step
double *R;
R= new double[N2];
//initial seed
int seed (11324);

for(int i=0;i<N2;++i) {
R[i]=randomwalk(seed,N,steplength);
++seed;
}
cout <<R[23];
delete[R];
return 0;
}

Can you give me the rest of the code?

#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

double randomwalk(int seed, int N, double steplength) {
//random number generator
unsigned int c(16807);
unsigned int p(21474837);
unsigned int *r;
double *randomnumb;
r= new unsigned int[N+1];
randomnumb=new double [N];
r[0]=seed;
randomnumb[0]=r[0];
randomnumb[0]=randomnumb[0]/p;
//generate random numbers
for(int i=1;i<N+1;++i) {
r[i]=r[i-1]*c%p;
randomnumb[i-1]=r[i];
randomnumb[i-1]=randomnumb[i-1]*2*3.14159265/p;
}
//x and y components of each vector
double *x,*y;
x= new double [N];
y= new double [N];
for(int i=0;i<N;++i) {
x[i]=cos(randomnumb[i])*steplength;
y[i]=sin(randomnumb[i])*steplength;
}
//measure the end to end vector
double Rx(0),Ry(0);
for(int i=0;i<N;++i) {
Rx=Rx+x[i];
Ry=Ry+y[i];
}
double R2;
R2=Rx*Rx+Ry*Ry;
delete[] r;
delete[] randomnumb;
delete[] x;
delete[] y;
return R2;
}

#ifndef SUBS_H_INCLUDED
#define SUBS_H_INCLUDED

double randomwalk(int seed, int N, double steplength)

#endif // SUBS_H_INCLUDED

And the header

Sorry, the last line «and the header» should be above:

#ifndef SUBS_H_INCLUDED
#define SUBS_H_INCLUDED

int N(10000); //number of steps for the randomwalk
int N2(1000); //number of randomwalks

These values, Right?

What is with these values?

The error message is: line 6 error: expected initializer before using

There is some problem with an initializer, but I don’t know what this means.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

int main()
{
	int N(10000); //number of steps for the randomwalk
	int N2(1000); //number of randomwalks
	double steplength(1); //length of one step
	double *R;
	R= new double[N2];
	//initial seed
	int seed (11324);

	for(int i=0;i<N2;++i) {
	R[i]=randomwalk(seed,N,steplength);
	++seed;
	}
	cout <<R[23];
	delete [R];    // delete []R; change it here
	return 0;
}

now work

correct me if I’m wrong but you have 3 files

main.cpp

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>
#include <cmath>
#include "subs.h"

using namespace std;

int main()
{
/* your code*/
}

subs.h

1
2
3
4
5
6
#ifndef SUBS_H_INCLUDED
#define SUBS_H_INCLUDED

double randomwalk(int seed, int N, double steplength)

#endif // SUBS_H_INCLUDED 

subs.cpp

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

double randomwalk(int seed, int N, double steplength)
{
/* your code*/
}

If this is what you mean your on the right track, but you need to understand how compiling works.
To put it in a simple way, the compiler will compile every cpp file separately first, doing a #include «something.h» will tell the compiler that some thing you call will be found in a other file (in this case something.h. But at this point the compiler has no clue where the code is only what will be in it. After this the linker will combine all these files to one binary. In your case the linker can’t find where the actual code for subs.h is (sins header and source files don’t need to have the same name or even be in the same location) This is why a source file needs to include it’s own header file to let the linker know what header file is linked to what source file. So you only need to add #include «subs.h» to the top of your subs.cpp file:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>
#include <cmath>
#include "subs.h"

using namespace std;

double randomwalk(int seed, int N, double steplength)
{
/* your code*/
}

And since you are using header safeguards the actual source will only be inserted ones (upon the first include) in the final binary.

(In a actual compiler and more advanced stuff it’s a bit more complicated then this, and the compiler/linker does many more things. But that’s stuff you don’t touch unless you know what you are doing.)

Ok, I added #include «subs.h» into my randomwalk.cpp file. I still get an error «expected initializer before double». It is in the randomwalk.cpp file. (6. Line)

To your first question, yes I have 3 files, only that the file subs.cpp is called randomwalk.cpp .

Last edited on

This is what I compiled on my computer and it worked fine:
If you still get a error with this, it’s not in the code.

What is the command you use to compile and link?

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include "randomwalk.h"
using namespace std;

int main()
{
	int N(10000); //number of steps for the randomwalk
	int N2(1000); //number of randomwalks
	double steplength(1); //length of one step
	double *R;
	R= new double[N2];
	//initial seed
	int seed (11324);

	for(int i=0;i<N2;++i) {
	R[i]=randomwalk(seed,N,steplength);
	++seed;
	}
	cout <<R[23];
	delete []R;    // delete []R; change it here
	return 0;
}

randomwalk.h

1
2
3
4
5
6
#ifndef RANDOMWALK_H_
#define RANDOMWALK_H_

double randomwalk(int seed, int N, double steplength);

#endif /* RANDOMWALK_H_ */ 

randomwalk.cpp

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
#include <iostream>
#include <fstream>
#include <cmath>
#include "randomwalk.h"

double randomwalk(int seed, int N, double steplength) {
//random number generator
unsigned int c(16807);
unsigned int p(21474837);
unsigned int *r;
double *randomnumb;
r= new unsigned int[N+1];
randomnumb=new double [N];
r[0]=seed;
randomnumb[0]=r[0];
randomnumb[0]=randomnumb[0]/p;
//generate random numbers
for(int i=1;i<N+1;++i) {
r[i]=r[i-1]*c%p;
randomnumb[i-1]=r[i];
randomnumb[i-1]=randomnumb[i-1]*2*3.14159265/p;
}
//x and y components of each vector
double *x,*y;
x= new double [N];
y= new double [N];
for(int i=0;i<N;++i) {
x[i]=cos(randomnumb[i])*steplength;
y[i]=sin(randomnumb[i])*steplength;
}
//measure the end to end vector
double Rx(0),Ry(0);
for(int i=0;i<N;++i) {
Rx=Rx+x[i];
Ry=Ry+y[i];
}
double R2;
R2=Rx*Rx+Ry*Ry;
delete[] r;
delete[] randomnumb;
delete[] x;
delete[] y;
return R2;
}

The file names were main.cpp, subs.h, randomwalk.cpp. Thanks for your help. It works when I copy your code (and change the difference in the file name).
I don’t know where my mistake war, but thanks for the help it works now.

As I was saying, the file names don’t matter as long as your #includes are correct.

main.cpp

1
2
3
4
5
6
7
8
#include <iostream>
#include "subs.h"
using namespace std;

int main()
{
 ...
}

subs.h

1
2
3
4
5
6
#ifndef RANDOMWALK_H_
#define RANDOMWALK_H_

double randomwalk(int seed, int N, double steplength);

#endif /* RANDOMWALK_H_ */  

randomwalk.cpp

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <fstream>
#include <cmath>
#include "subs.h"

double randomwalk(int seed, int N, double steplength)
{
   ...
}

will work fine too.

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;        
}
  • Печать

Страницы: [1]   Вниз

Тема: Ошибка при попытке использовать iostream  (Прочитано 1549 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
tetramin

Добрый день.

Я пытался написать программу типа хелловорлд.
Компилятор показывет столько ошибок, что они не помещаются на стандартный вывод.
Думая, что ошибка где-то либо в using namespace std, или в std::cout << …, я решил попробовать оставить только это:

#include <iostream>

int main ()
{
return 0;
}


Файл iostream, вместе со всеми, прописанными в нём, есть в /usr/include/c++/4.4/bits
Как я понял в итоге, проблема именно в этих файлах.

Ребята, в чём у меня проблема. Пробовал переустанавливать g++. Не помогает.


Оффлайн
__v1tos

sudo apt-get install build-essential
Как компилируете?

AMD Phenom II 945, GA-MA790GPT-UD3H (HD 3300), 5 GiB ram


Оффлайн
Mam(O)n

Подозреваю, что компилируешь не с помощью g++. Ибо УМВР.


Оффлайн
tetramin

build-essential у меня установлен

А компилирую так:

$ g++ -o hiall hiall.cpp

Я тут ещё попробовал math.h включить:
Часть кода:

/usr/include/c++/4.4/stdio.h:140: error: expected initializer before ‘__getStream’
/usr/include/c++/4.4/stdio.h:149: error: expected initializer before ‘clearerr’
/usr/include/c++/4.4/stdio.h:150: error: expected initializer before ‘fclose’
/usr/include/c++/4.4/stdio.h:151: error: expected initializer before ‘fflush’
/usr/include/c++/4.4/stdio.h:152: error: expected initializer before ‘fgetc’
/usr/include/c++/4.4/stdio.h:153: error: expected initializer before ‘fgetwc’
...
/usr/include/c++/4.4/stdio.h:363: error: ‘std::__getStream’ has not been declared
/usr/include/c++/4.4/stdio.h:364: error: ‘std::_fcloseall’ has not been declared
/usr/include/c++/4.4/stdio.h:365: error: ‘std::_fdopen’ has not been declared
/usr/include/c++/4.4/stdio.h:366: error: ‘std::_fgetc’ has not been declared
/usr/include/c++/4.4/stdio.h:367: error: ‘std::_fgetchar’ has not been declared
/usr/include/c++/4.4/stdio.h:368: error: ‘std::_fgetwc’ has not been declared
...
/usr/include/c++/4.4/math.h:152: error: expected initializer before ‘atan’
/usr/include/c++/4.4/math.h:153: error: expected initializer before ‘atan2’
/usr/include/c++/4.4/math.h:154: error: expected initializer before ‘ceil’
/usr/include/c++/4.4/math.h:155: error: expected initializer before ‘cos’
/usr/include/c++/4.4/math.h:156: error: expected initializer before ‘cosh’
...

Что же это такое…?

« Последнее редактирование: 13 Февраля 2011, 10:35:24 от tetramin »


Оффлайн
Mam(O)n

Обычно главная ошибка идёт первой в списке, остальное это лишь последствия.


Оффлайн
__v1tos

А как организовать вывод g++ в файл, что бы увидеть эти ошибки?
Я имею в виду перенаправить вывод в файл


Пользователь решил продолжить мысль 13 Февраля 2011, 11:01:35:


Нашел, попробуйте

g++ -o hiall hiall.cpp &> 1.txt

« Последнее редактирование: 13 Февраля 2011, 11:01:35 от __v1tos »

AMD Phenom II 945, GA-MA790GPT-UD3H (HD 3300), 5 GiB ram


Оффлайн
tetramin

И меня такая команда интересовала), спасибо.

Вот начало вывода компилятора:

Это в случае iostream


Оффлайн
__v1tos

Всетаки у вас что то не то установлено.
У меня например здесь файла           /usr/include/c++/4.4/stddef.h         нет
и             /usr/include/c++/4.4/_stddef.h:108: error: ‘__cdecl’ does not name a type
еще не видел ни в одном файле соглашения о вызовах __cdecl (в g++ такие вещи не нужны)

AMD Phenom II 945, GA-MA790GPT-UD3H (HD 3300), 5 GiB ram


Оффлайн
Mam(O)n

In file included from /usr/include/c++/4.4/stddef.h:25,

Интересно, как это у тебя заголовочный файл из простого «C» затисался в «C++» каталог? Мне кажется, что тебе придётся грохнуть этот каталог (/usr/include/c++/4.4) полностью и переустановить пакеты, которые подскажет команда dpkg -S /usr/include/c++/4.4


Оффлайн
tetramin

Снёс каталог /usr/include/c++/4.4
dpkg -S сказала, что нужно поставить libstdc+++-4.4. Поставил.
Попробовал скомпилировать. Ошибок значительно меньше стало. Теперь он просто говорил, что нет файла wchar.h
Я его скопировал из бэкапа папки 4.4 (которую как бы снёс).
Далее он начал ругаться на отсутствие locate.h
С ним я поступил так же, только скопировал его из папки /usr/include/bits
Ошибок стало больше… Решив, что проблема в каталоге /usr/include/bits и ещё, что такое копирование ни к чему хорошему не приведёт я просто написал

dpkg -S /usr/include/bits На что она мне ответила libc6-dev

Решилась проблема сносом и переустановкой libc6-dev и иже с ней.
Всем спасибо огромное!


  • Печать

Страницы: [1]   Вверх

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