Expected initializer before function name - c++

#include <iostream>
#include <string>
using namespace std;
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
}
sotrudnik create(string n,string spec,string raz,int sal) {
sotrudnik temp;
temp.name=n;
temp.speciality=spec;
temp.razread=raz;
temp.zarplata=sal;
return temp;
}
*sotrudnik str_compare (string str1, string str2, sotrudnik sot1, sotrudnik sot2)
I try to learn C++. But when i try to compile this code with GCC-4.4.5 by using the options " g++ -Wall -c ", I get the following error:
g++ -Wall -c "lab2.cc" (in directory: /home/ion/Univer/Cpp)
lab2.cc:11: error: expected initializer before create
lab2.cc:20: error: expected constructor, destructor, or type conversion before str_compare
Compilation failed.
Both errors are tied to the function declarations. (round 11 is the declaration of function create, round 20 - of the function str_compare). Tried to google for these kinds of errors, but couldn't find examples of similar errors, as the error messages are very generic. How can I understand their meaning and how to solve them? Thank you very much for your attention.

You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*

Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here

Related

The code works perfectly when I substitute char with string.why so?

The below code works perfectly with strings but with char it gives segmentation fault.
#include<iostream>
using namespace std;
class salary
{
public:
int empno;
float inctax;
float netsal;
int gross;
short int age;
char name[50];
salary(){
empno=0;
gross=0;
age=0;
strcpy(name,'\0');
}
salary(int empn,int gros,short int ag,char nam[]){
empno=empn;
gross=gros;
age=ag;
strcpy(name,nam);
}
void calc(){
inctax=0.0;
if(gross>1000000)
inctax=0.3*gross;
else if(gross>=500000 && gross<=1000000)
inctax=0.2*gross;
else if(gross>=250000 && gross<500000)
inctax=0.1*gross;
else
inctax=0.0;
netsal=gross-inctax;
cout<<"inctax"<<inctax;
cout<<"net sal"<<netsal;
}
};
int main(){
salary *r=new salary();
salary *r1=new salary(112,500000,21,"Arnab");
r1->calc();
return 0;
}
I agree with vu1p3n0x's comment,
the problem is in the default constructor.
strcpy(name, '\0'); // This is wrong!
strcpy() takes two char arrays as arguments, but a character itself was passed as the second argument in your code.
The syntax of strcpy() is:
char * strcpy ( char * destination, const char * source );
In order to create null string using char arrays, you should probably use,
strcpy(name, "\0");
/*or*/
name[0] = '\0';
More on copying string, Reference and tutorialspoint
Your main problem is that your compiler isn't telling you about the obvious errors in the code. If you have correctly told it to report errors, then you perhaps need a better compiler. Here's the output I get when I compile:
g++ -std=c++14 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses 38113648.cpp -o 38113648
38113648.cpp: In constructor ‘salary::salary()’:
38113648.cpp:18:25: error: ‘strcpy’ was not declared in this scope
strcpy(name,'\0');
^
38113648.cpp: In constructor ‘salary::salary(int, int, short int, char*)’:
38113648.cpp:25:24: error: ‘strcpy’ was not declared in this scope
strcpy(name,nam);
^
38113648.cpp: In function ‘int main()’:
38113648.cpp:46:48: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
salary *r1=new salary(112,500000,21,"Arnab");
^
38113648.cpp:45:13: warning: unused variable ‘r’ [-Wunused-variable]
salary *r=new salary();
^
When I add
#include <cstring>
and change the constructor to take char const[], I get
g++ -std=c++14 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses 38113648.cpp -o 38113648
38113648.cpp: In constructor ‘salary::salary()’:
38113648.cpp:19:25: warning: null argument where non-null required (argument 2) [-Wnonnull]
strcpy(name,'\0');
^
Obviously you meant that to be "\0". Better still, provide an initializer:
salary()
: empno{0},
gross{0},
age{0},
name{0}
{
}
salary(int empno, int gross, short int age, char const name[])
: empno{empno},
gross{gross},
age{age}
{
strcpy(this->name, name);
}
(I've also given the formal parameters more meaningful names, as this often forms the documentation of the constructor).
Adding -Weffc++ may also be worthwhile - in this case it warns that you don't initialize inctax or netsal in the constructors. If you're happy to have part-initialized objects, you'll obviously need to use Valgrind to check that these values are indeed set before they are used, because it can't be determined statically.

What is wrong with my code? I can't compile it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
So the objective of this program is to display the initials of a name typed in by the user. So if I type James Issac Newton, it should give me JIN. I tried compiling my code in the terminal using g++ -Wall -o name name.cpp but it wouldn't compile. What exactly am I doing wrong??
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{
char name[100];
gets(name);
char a,b,c;
cin>>name;
a=name[0];
int x;
for (int i=0;i<=strlen(name);i++)
{
if (name[i]==" ")
{
b=name[i+1];
x=i;
break;
}
}
for (int j=x;j<=strlen(name);j++)
{
if (name[j]==" ")
{
c=name[j+1];
}
}
cout<<a<<b<<c;
return 0;
}
Compiler error messages:
The name of my file is acro.cpp acro.cpp:
In function âint main()â:
acro.cpp:8:2: warning: âchar* gets(char*)â is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
acro.cpp:8:11: warning: âchar* gets(char*)â is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations] acro.cpp:13:29: error: âstrlenâ was not declared in this scope
Since you declared:
char name[100];
then name[i] (if i is a valid index) is a char. But " " is not a character literal, but a string; you should code
if (name[j]==' ')
BTW, you should read more about C++ (and its std::string) and consider declaring
std::string name;
and adapting the rest of your program to make that work. BTW, compile with all warnings & debug info (g++ -Wall -Wextra -g) and learn how to use the debugger (gdb)
Presumably, the compiler told you what's wrong, but you forgot to provide that information. My compiler says
‘strlen’ was not declared in this scope
because you forgot to include the header <cstring> that defines it.
Then it says
ISO C++ forbids comparison between pointer and integer
That's a bit trickier to interpret; it refers to this
if (name[i]==" ")
where you try to compare a character (which converts to an integer) with a string (which converts to a pointer). Instead, compare with another character:
if (name[i]==' ')
^ ^
Once it compiles, get rid of gets(name);. It does the same thing as cin >> name;, but is (perhaps) even more dangerous. Then consider using std::string rather than a C-style char array; that way, your program won't explode if you enter more than 100 characters.
Apart from compiler errors you have done one more mistake :-
gets(name);
char a,b,c;
cin>>name;
second cin would overide first value you have entered using gets.

gcc error "expected ')' before '[' token"

I am receiving these errors while attempting to compile my program with GCC and i'm not sure whats causing them.
functions.h:21: error: expected ')' before '[' token
functions.h:22: error: expected ')' before '[' token
functions.h:23: error: expected ')' before '[' token
functions.h:25: error: expected ')' before '[' token
functions.h:26: error: expected ')' before '[' token
functions.h:27: error: expected ')' before '[' token
My program compiles fine in visual studio 2012.
Heres the header file that seems to be causing the errors.
struct subject
{
char year[5];
char session;
char code[8];
char credit[3];
char mark[4];
};
struct data
{
char name[30];
char id[30];
char cc[30];
char course[80];
struct subject subjects[30];
int gpa;
};
void displayRecord(data [], int);
int nameSearch(data [], char [], int [], int);
void editRecord(data [], int, int);
char getChar(const char [], int);
int getData(data []);
void displayData(data []);
void deleteRecord(data [], int, int);
I'm invoking the compiler like this:
gcc -o test functions.cpp functions.h main.cpp
I'm stumped so any help would be appreciated!
My psychic debugging powers tell me that your visual studio is compiling the code as C++ while gcc is compiling it as C. Since you're missing the struct keyword before data in your function parameters the C compiler doesn't know what to do. Try running it through g++ instead of gcc (and possibly make sure your including source file's extension is .C or .cpp.
The problem is that you are passing functions.h to the compiler. That is an include file and you should just let the two .cpp files include it. There's no need to pass it in your command line invocation of the compiler. Simply remove functions.h from your command line invocation of gcc.
Since this is C++, you should be using g++ rather than gcc to compile. Since you used gcc, the compiler treated functions.h as being C, and the code not valid C.
So, I think your compilation should be
g++ -o test functions.cpp main.cpp

Understanding 'using' keyword : C++

Can someone please explain below output:
#include <iostream>
using namespace std;
namespace A{
int x=1;
int z=2;
}
namespace B{
int y=3;
int z=4;
}
void doSomethingWith(int i) throw()
{
cout << i ;
}
void sample() throw()
{
using namespace A;
using namespace B;
doSomethingWith(x);
doSomethingWith(y);
doSomethingWith(z);
}
int main ()
{
sample();
return 0;
}
Output:
$ g++ -Wall TestCPP.cpp -o TestCPP
TestCPP.cpp: In function `void sample()':
TestCPP.cpp:26: error: `z' undeclared (first use this function)
TestCPP.cpp:26: error: (Each undeclared identifier is reported only once for each function it appears in.)
I have another error:
error: reference to 'z' is ambiguous
Which is pretty clear for me: z exists in both namespaces, and compiler don't know, which one should be used. Do you know? Resolve it by specifying namespace, for example:
doSomethingWith(A::z);
using keyword is used to
shortcut the names so you do not need to type things like std::cout
to typedef with templates(c++11), i.e. template<typename T> using VT = std::vector<T>;
In your situation, namespace is used to prevent name pollution, which means two functions/variables accidently shared the same name. If you use the two using together, this will led to ambiguous z. My g++ 4.8.1 reported the error:
abc.cpp: In function ‘void sample()’:
abc.cpp:26:21: error: reference to ‘z’ is ambiguous
doSomethingWith(z);
^
abc.cpp:12:5: note: candidates are: int B::z
int z=4;
^
abc.cpp:7:5: note: int A::z
int z=2;
^
which is expected. I am unsure which gnu compiler you are using, but this is an predictable error.
You get a suboptimal message. A better implementation would still flag error, but say 'z is ambiguous' as that is the problem rather than 'undeclared'.
At the point name z hits multiple things: A::z and B::z, and the rule is that the implementation must not just pick one of them. You must use qualification to resolve the issue.

why can't use the 'link' as a name of class

As the title mentioned. The following code shows error :
#include <iostream>
using namespace std;
class link
{
public:
link()
{
num=0;
next=NULL;
}
int num;
link* next;
};
int main() {
link test;
return 0;
}
compile this code with
g++ test.cpp -o test
my g++ versions is
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
And the compiler shows the following error
test.cpp: In function ‘int main()’:
test.cpp:18:10: error: expected ‘;’ before ‘test’
If I comment this 'link test' statement, then everything is ok.
Besides, if I replace 'link' with other name like 'Link', everything is ok too.
In Visual Studio or VC, the code is ok.... So it confused me very much.
To summarize the comments:
GCC includes a function named link. For C compatibility, C++ allows you to define a struct (or class) with the same name as a function, but you have to disambiguate them on use.
I.e. in this case, the fix is class link test;
The use of link inside the definition of class link is an exception, there it always refers to the class itself. This is necessary to be able to write the constructor, as you can't disambiguate the name there. There's no syntax which would allow it.
There is a int link(const char *path1, const char *path2); function in unistd.h, which appears to be included from iostream. Gcc has had some problems with this kind of problem in the past. (I note that 4.7.2 doesn't show this behavior.)
As noted by MSalters, adding a
class link test;
should disambiguate the problem.