-
05-29-2014
#1
Registered User
Error: Two or more data types in declaration of main
Could somebody help me? Thanks!
insert
Code:
#include <stdio.h> #include <string.h> #define P printf #define S scanf struct person { char name[20]; int age; char relationship[200]; } int main() { FILE *storage; int a, b, c; char ch; char password [20]; char passwordinput [20]; P("Welcome to Recentive Client Database Managing 1.0.n"); P("Do not use spaces in any data entries, and substitute with underscores to prevent the occurrence of program errors.n"); P("Please input your password.n"); strcpy(password, "clevel"); S("%s", &passwordinput); c = strcmp(password, passwordinput); if(c == 0) { P("Access granted.n"); } else { P("Access denied.n"); return 0; } label: P("Type one of the following integers to perform a specific action:n1- add new clientn2- access database client listn3- clear storage file contentsn4- start emergency data protectionn5- terminate database operationn"); S("%d", &a); if(a == 1) { P("Add new client.n"); struct person client1; P("Enter client name:n"); S("%s", &client1.name); P("Enter client age:n"); S("%d", &client1.age); P("Enter client relationship to the company:n"); S("%s", &client1.relationship); storage = fopen("storage.txt", "a"); fprintf(storage,"n%st%dt%s",client1.name, client1.age, client1.relationship); fclose(storage); P("Client has been added.n"); goto label; } else if(a == 2) { P("Access database clients.n"); storage = fopen("storage.txt", "r"); while((ch = fgetc(storage)) != EOF) P("%c",ch); fclose(storage); P("n"); P("Press any number key to go to main menun"); S("%s",&b); if(b > 0 || b < 100) { goto label; } else if(b > 100 || b < 1000) { goto label; } else { goto label; } } else if(a == 3) { storage = fopen("storage.txt", "w+"); fclose(storage); P("Storage file has been cleared.n"); goto label; } else if(a == 4) { printf("Emergency safety protocol in effect.n"); while(1) { printf("trolololololo Napoleonn"); } } else { P("Terminating.nThank you for using Recentive Client Database Managing 1.0.n"); return 0; } }
-
05-29-2014
#2
Registered User
Always compile with the warning level set to max (e.g. -Wall flag for gcc, else read your compiler documentation). You should see something like:
Code:
$ make foo gcc -Wall -ggdb3 -pedantic -std=gnu99 -O0 -o foo foo.c -lm -lpthread -lrt foo.c:14:1: error: expected ‘;’, identifier or ‘(’ before ‘int’ foo.c: In function ‘main’: foo.c:25:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat] foo.c:44:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat] foo.c:48:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[200]’ [-Wformat] foo.c:64:9: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int *’ [-Wformat] make: *** [foo] Error 1
Line 14: struct definitions require a ; to terminate them, thus the Compiler doesn’t think you’re done, and isn’t expecting a function definition like main.
Lines 25, 44, 48: scanf requires a pointer to where it will store the scanned data. The name of an array, without any indexing [ ] brackets, is a pointer to the first element. Thus, you don’t need the & for parameters for the %s format specifier.
Line 64: You need to use a different format specifier to read ints with scanf. I suggest you read a textbook/tutorial or the scanf documentation.Other notes:
- Defining printf as P and scanf as S is a bad idea. All it does is reduce readability. Clear, readable code is paramount and you should never sacrifice clarity or readability because you’re too lazy to type a few extra characters.
- Some of your variable names could be better. In particular, a, b and c. Again, don’t sacrifice clarity. For example, a should probably be called something like menu_choice. c is not needed (you can put the strcmp call directly in the if condition), but if you want to use it, a name like password_compare would be better.
- There are very few reasons you should use goto, especially as a beginner (link). It makes program control flow difficult to follow/reason about, meaning bugs are more likely. Again, clear, readable code is paramount. To repeat sections of code, use a loop.
- You should avoid using magic nubmers (link). Instead, #define a constant with a sensible name like MAX_NAME, MAX_RELATIONSHIP and MAX_PASSWORD, which allows you to change them easily by changing one line (the define). And yes, define MAX_NAME and MAX_PASSWORD separately since you may want to make one longer/shorter without changing the other.
- Read up on fgetc. It returns an int, not a char. Thus you need to declare ch as an int. This is so fgetc can return every possible char value, as well as special values like EOF.
- Always check return values of fopen before proceeding. If fopen fails, your file pointer is NULL, and trying to do something with it (e.g. fgetc, fclose) will attempt to access data at the NULL address, which results in undefined behavior (anything or nothing can happen). In your specific cases, it will likely result in a program crash due to seg fault.
There’s probably more, but that should keep you busy for a while.
-
05-29-2014
#3
Registered User
polimorf96 9 / 9 / 1 Регистрация: 02.08.2010 Сообщений: 270 |
||||
1 |
||||
где ошибка?14.11.2010, 00:58. Показов 4142. Ответов 9 Метки нет (Все метки)
Компилятор ругается : хотел создать «породие» на класс string чисто в целях обучения но не могу понять почему ошибка то? вот исходник .
__________________
0 |
alex_x_x бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
||||
14.11.2010, 01:03 |
2 |
|||
0 |
ForEveR В астрале 8048 / 4805 / 655 Регистрация: 24.06.2010 Сообщений: 10,562 |
||||
14.11.2010, 01:05 |
3 |
|||
; после определения класса забыли.
0 |
5 / 5 / 4 Регистрация: 11.10.2009 Сообщений: 24 |
|
14.11.2010, 01:06 |
4 |
И еще в С++ нет оператора or так что замените его на ||
0 |
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
14.11.2010, 01:08 |
5 |
кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения Добавлено через 13 секунд
И еще в С++ нет оператора or так что замените его на || есть)) xor, and, not есть
0 |
В астрале 8048 / 4805 / 655 Регистрация: 24.06.2010 Сообщений: 10,562 |
|
14.11.2010, 01:08 |
6 |
Но не везде. В студии нету к примеру)
0 |
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
14.11.2010, 01:13 |
7 |
Но не везде. В студии нету к примеру) _______________ The <iso646.h> header shall define the following eleven macros (on the left) that expand to the corresponding tokens (on the right): Добавлено через 2 минуты
2 |
В астрале 8048 / 4805 / 655 Регистрация: 24.06.2010 Сообщений: 10,562 |
|
14.11.2010, 01:18 |
8 |
alex_x_x, Снимаю шляпу. Не подозревал о таком хедере. Спасибо за информацию!
0 |
polimorf96 9 / 9 / 1 Регистрация: 02.08.2010 Сообщений: 270 |
||||
14.11.2010, 17:03 [ТС] |
9 |
|||
; после определения класса забыли.
точно блин такая ошибка дурацка! СПАСИБО! Добавлено через 1 минуту
кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения Добавлено через 13 секунд есть)) xor, and, not есть кстати интересно что компилятор на [] не выдает, что не все пути возвращают значения
0 |
бжни 2473 / 1684 / 135 Регистрация: 14.05.2009 Сообщений: 7,162 |
|
15.11.2010, 00:02 |
10 |
обязана что-то вренуть в любом случае -так чтоли? как-то так
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
15.11.2010, 00:02 |
10 |
Здравствуйте. Не могу понять в чем проблема. Не компилируется. Ошибок во весь экран:
root@debian:~/state-devs# make
gcc -c main.c -Wall -I. -std=gnu99 -pedantic -march=native -O2 -Wno-pointer-arit h -Wno-address
In file included from configs.h:15:0,
from main.c:12:
state.h:18:1: error: two or more data types in declaration specifiers
bool state_run(void);
^
In file included from main.c:13:0:
state.h:18:1: warning: ISO C forbids forward parameter declarations [-Wpedantic]
bool state_run(void);
^
In file included from /usr/include/stdio.h:33:0,
from devlist.h:15,
from log.h:16,
from main.c:14:
/usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h:212:23: error: storage class specified for parameter ‘size_t’
typedef __SIZE_TYPE__ size_t;
^
In file included from /usr/include/stdio.h:35:0,
from devlist.h:15,
from log.h:16,
from main.c:14:
/usr/include/x86_64-linux-gnu/bits/types.h:30:23: error: storage class specified for parameter ‘__u_char’
typedef unsigned char __u_char;
^
/usr/include/x86_64-linux-gnu/bits/types.h:31:28: error: storage class specified for parameter ‘__u_short’
typedef unsigned short int __u_short;
^
/usr/include/x86_64-linux-gnu/bits/types.h:32:22: error: storage class specified for parameter ‘__u_int’
typedef unsigned int __u_int;
^
/usr/include/x86_64-linux-gnu/bits/types.h:33:27: error: storage class specified for parameter ‘__u_long’
typedef unsigned long int __u_long;
^
/usr/include/x86_64-linux-gnu/bits/types.h:36:21: error: storage class specified for parameter ‘__int8_t’
typedef signed char __int8_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:37:23: error: storage class specified for parameter ‘__uint8_t’
typedef unsigned char __uint8_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:38:26: error: storage class specified for parameter ‘__int16_t’
typedef signed short int __int16_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:39:28: error: storage class specified for parameter ‘__uint16_t’
typedef unsigned short int __uint16_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:40:20: error: storage class specified for parameter ‘__int32_t’
typedef signed int __int32_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:41:22: error: storage class specified for parameter ‘__uint32_t’
typedef unsigned int __uint32_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:43:25: error: storage class specified for parameter ‘__int64_t’
typedef signed long int __int64_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:44:27: error: storage class specified for parameter ‘__uint64_t’
typedef unsigned long int __uint64_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:52:18: error: storage class specified for parameter ‘__quad_t’
typedef long int __quad_t;
^
/usr/include/x86_64-linux-gnu/bits/types.h:53:27: error: storage class specified for parameter ‘__u_quad_t’
typedef unsigned long int __u_quad_t;
^
In file included from /usr/include/stdio.h:35:0,
from devlist.h:15,
from log.h:16,
from main.c:14:
/usr/include/x86_64-linux-gnu/bits/types.h:124:25: error: storage class specifie d for parameter ‘__dev_t’
__STD_TYPE __DEV_T_TYPE __dev_t; /* Type of device numbers. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:125:25: error: storage class specifie d for parameter ‘__uid_t’
__STD_TYPE __UID_T_TYPE __uid_t; /* Type of user identifications. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:126:25: error: storage class specifie d for parameter ‘__gid_t’
__STD_TYPE __GID_T_TYPE __gid_t; /* Type of group identifications. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:127:25: error: storage class specifie d for parameter ‘__ino_t’
__STD_TYPE __INO_T_TYPE __ino_t; /* Type of file serial numbers. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:128:27: error: storage class specifie d for parameter ‘__ino64_t’
__STD_TYPE __INO64_T_TYPE __ino64_t; /* Type of file serial numbers (LFS).*/
^
/usr/include/x86_64-linux-gnu/bits/types.h:129:26: error: storage class specifie d for parameter ‘__mode_t’
__STD_TYPE __MODE_T_TYPE __mode_t; /* Type of file attribute bitmasks. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:130:27: error: storage class specifie d for parameter ‘__nlink_t’
__STD_TYPE __NLINK_T_TYPE __nlink_t; /* Type of file link counts. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:131:25: error: storage class specifie d for parameter ‘__off_t’
__STD_TYPE __OFF_T_TYPE __off_t; /* Type of file sizes and offsets. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:132:27: error: storage class specifie d for parameter ‘__off64_t’
__STD_TYPE __OFF64_T_TYPE __off64_t; /* Type of file sizes and offsets (LFS). */
^
/usr/include/x86_64-linux-gnu/bits/types.h:133:25: error: storage class specifie d for parameter ‘__pid_t’
__STD_TYPE __PID_T_TYPE __pid_t; /* Type of process identifications. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:134:26: error: storage class specifie d for parameter ‘__fsid_t’
__STD_TYPE __FSID_T_TYPE __fsid_t; /* Type of file system IDs. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:135:27: error: storage class specifie d for parameter ‘__clock_t’
__STD_TYPE __CLOCK_T_TYPE __clock_t; /* Type of CPU usage counts. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:136:26: error: storage class specifie d for parameter ‘__rlim_t’
__STD_TYPE __RLIM_T_TYPE __rlim_t; /* Type for resource measurement. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:137:28: error: storage class specifie d for parameter ‘__rlim64_t’
__STD_TYPE __RLIM64_T_TYPE __rlim64_t; /* Type for resource measurement (LFS). */
^
/usr/include/x86_64-linux-gnu/bits/types.h:138:24: error: storage class specifie d for parameter ‘__id_t’
__STD_TYPE __ID_T_TYPE __id_t; /* General type for IDs. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:139:26: error: storage class specifie d for parameter ‘__time_t’
__STD_TYPE __TIME_T_TYPE __time_t; /* Seconds since the Epoch. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:140:30: error: storage class specifie d for parameter ‘__useconds_t’
__STD_TYPE __USECONDS_T_TYPE __useconds_t; /* Count of microseconds. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:141:31: error: storage class specifie d for parameter ‘__suseconds_t’
__STD_TYPE __SUSECONDS_T_TYPE __suseconds_t; /* Signed count of microseconds. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:143:27: error: storage class specifie d for parameter ‘__daddr_t’
__STD_TYPE __DADDR_T_TYPE __daddr_t; /* The type of a disk address. */
^
/usr/include/x86_64-linux-gnu/bits/types.h:144:25: error: storage class specifie d for parameter ‘__key_t’
__STD_TYPE __KEY_T_TYPE __key_t; /* Type of an IPC key. */
^
Makefile:12: ошибка выполнения рецепта для цели «main.o»
make: *** [main.o] Ошибка 1
root@debian:~/state-devs#
I get «two or more data types in declaration of `SDL_main'». Why??
my main.cpp
#include "Globals.h"
//cShip ship1;
int main (int argc, char* argv[])
{
Init();
Quit();
return 0;
}
my globals.h
#ifndef _GLOBALS_
#define _GLOBALS_
#include "SDL.h"
#include "INandOUT.h"
#include "cEntity.h"
#include "cMobile.h" //derived from cEntity
#include "cShip.h" //derived from cMobile
#endif
Lovely errors:
main.cpp:6: error: new types may not be defined in a return type
main.cpp:6: error: two or more data types in declaration of `SDL_main’
main.cpp:6: error: two or more data types in declaration of `SDL_main’
main.cpp:6: error: two or more data types in declaration of `SDL_main’
main.cpp:6: error: extraneous `int’ ignored
main.cpp: In function `flag SDL_main(int, char**)’:
main.cpp:6: error: new declaration `flag SDL_main(int, char**)’
D:/Data/SDL crap/SDL-1.2.11/include/SDL_main.h:53: error: ambiguates old declaration `int SDL_main(int, char**)’
main.cpp: In function `flag SDL_main(int, char**)’:
main.cpp:11: error: invalid conversion from `int’ to `flag’
make.exe: *** [main.o] Error 1
Execution terminated
EDIT: Crap, I just realized this thread is in the Beginners, I meant to put it in Alternate Libs
I don’t use SDL, so I’m just tossing out ideas, but from here, I would check that:
(1) You’ve linked against the libraries properly
(2) Richard uses sdl_main.h — why are you not using it?
(3) You don’t have any variable/function named main
Quote:Enginuity, part 4
The Entry Point and Task Pool; or, Swim Your Way In…I’ll just say this: make absolutely sure that the main() function has a header like the one above. Same return type, same name, same argument types. If you get errors about ‘sdl_main is undefined,’ check here. (The truth is that sdl_main.h includes a macro to turn any function named main() into one named sdl_main(), so that it doesn’t get confused with the main() function that SDL provides. As far as I can tell, an unfortunate side effect of this is that you shouldn’t use the name ‘main’ for any functions or variables; but frankly, I consider it a small price to pay).
I think my #includes are wrong. I always found them so darn confusing. Putting «#include SDL.h» in the main.cpp and deleting everything else works fine…
but getting rid of Globals.h and doing this to main doesn’t work:
#include "SDL.h"#include "INandOUT.h"#include "cEntity.h"#include "cMobile.h" //derived from cEntity#include "cShip.h" //derived from cMobile//cShip ship1;int main (int argc, char* argv[]){ return 0;}
I get the exact same errors…. WTF. Sometimes I think Dev-CPP is giving me **** for no reason.
are your includes guarded with
#ifndef MYFILE_H_ #define MYFILE_H_//put all the header stuff here#endif
? This stops against the preprocessor including the same .h file multiple times
Quote:Putting «#include SDL.h» in the main.cpp and deleting everything else works fine…
Ok. This tells us something. Add the inclues one by one until it breaks. This should help you narrow down the problem. Post the include files (as long as there aren’t 10+!!!), so we can take a look at them.
I figured out what was causing it:
In cShip.cpp I have
That is supposed to be the implementation of cShip.
So… I guess I really don’t know how #includes work.
I want to have my main.cpp to be able to use a bunch of functions and classes kept separate in .h and .cpp files. How can I have them work together without running into duplications?
Another problem I had with a text RPG I made with classes was that I ended up «locking» myself out of certain data I needed and ended up having to copy code in some functions.
Quote:Another problem I had with a text RPG I made with classes was that I ended up «locking» myself out of certain data I needed and ended up having to copy code in some functions.
Ahhh yes…You need to make sure you design your classes so they are more modular. As well, think about «Getter» and «Setter» functions. Example:
class player{private:int health;int mana;public:void SetHealth(int h);void SetMana(int m);int GetHealth();int GetMana();}
This helps hide the underlying functionality (think of vector’s insert()), which still allowing you to get informaton about the class.
If two class really must know about each other, you can declare one a friend of the other.
Quote:So… I guess I really don’t know how #includes work.
I’m not sure if you have read any books, but take a look here. If you have any questions, post a new thread, and we can help you out.
The .h file should have the function prototypes and class defnitions, the .cpp should have function implimentations. What you’re doing, ie the #include «cShip.h» in cShip.cpp is correct. What does cShip.h look like?
//cShip.h//cMobile class derived to cShipclass cShip : public cMobile{ public: cShip(); void Move(); int getX(); int getY(); ~cShip(); private: int itsAngle; int itsVel;}
The real question is: how do I connect main.cpp, with all the other classes?
Every time I include Global.h in a .cpp I get another duplicate error thing. I have guards around the whole block (see Globals.h 1st post). I even tried doing them individually, and it’s the same problem.
The way I have it set up now is like this:
«main.cpp» #includes «globals.h» —this causes a duplicate
«globals.h» #includes ALL of the .h files, as well as SDL.h
«cShip.cpp» #includes «globals.h» —this cause another duplicate
…how does one do this correctly?
Well there is no reason for cShip.cpp to include globals.h. It doesn’t need to know about all your other classes. cShip.cpp should just include cShip.h, which in turn should ONLY include the header files for things it needs to know about.
So (I am not sure what INandOUT.h does…):
globals.h should include
— #include «SDL.h»
— #include «INandOUT.h»
— #include «cShip.h»
cMobile.h should include cEntity.h
cMobile.cpp should include cMobile.h
cShip.h should include cMobile.h
cShip.cpp should include cShip.h
main.cpp should then include globals.h
You will then have access to your cShip from within your main function.
As well, at the end of a class definition, you need a ; after then ending brace
class myClass{private:int blah;};
You seem to be missing this in your example. This would cause you massive grief if you were trying to compile w/o it.
I need to run to class, but let me know if that helps at all.
I realized I was missing the ; and fixed them.
That helps a lot. No errors and looks like I can access everything I need so far.
INandOUT contains my Init() function which loads resources like pics, sounds and text files. Quit() does the opposite so I don’t have any memory leaks.
I’ll probably be back here again, because I have a feeling I’ll run into some structuring problems… I always do..
Thank you _Sigma, I left you a present in the form of a radio button.
Well glad you got it sorted out!
Quote:
Thank you _Sigma, I left you a present in the form of a radio button.
heh thanks!