I’ve got error:
main.c(10) : error C2059: syntax error : 'type'.
What’s wrong with this code?
#include <stdio.h>
#include <stdlib.h>
void getline(FILE* file, char* line)
{
int c;
size_t n = 0;
while(c=fgetc(file)!='\n')
{
line[n++] = char(c);
}
line[n] = '\0';
}
int main(int argc, char* argv[])
{
FILE* f;
char* line = (char*)malloc(100);
f = fopen("Saxo","r");
if(f==NULL)
return -1;
getline(f,line);
free(line);
fclose(f);
return 0;
}
Kiril Kirov
37.5k22 gold badges115 silver badges187 bronze badges
asked Mar 21, 2014 at 12:45
3
line[n++] = char(c);
is a syntax error. I guess you meant to cast:
line[n++] = (char)c;
NB. This cast actually has no effect, as int
can be implicitly converted to char
, which happens anyway because line[n++]
has type char
.
It would also be wise to check against EOF
as well as \n
in your loop, in case the file does not end with a newline.
Also: =
has lower priority , so the line while(c=fgetc(file)!='\n')
is going to set c
to either 1
or 0
. Some parentheses required to fix.
answered Mar 21, 2014 at 12:50
M.MM.M
139k21 gold badges208 silver badges365 bronze badges
3
Considering your name this probably is a confusion since C++ allows what are called explicit type conversions which are an expression:
line[n++] = char(c);
so this would compile fine in C++ but this does not exist in C so what you need to use is a plain cast:
line[n++] = (char)c;
but is not necessary in this case.
I would advise cranking up the warnings that would have indicated that this line is a problem:
while(c=fgetc(file)!='\n')
clang
warns us by default while gcc
does not:
warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
while(c=fgetc(file)!='\n')
~^~~~~~~~~~~~~~~~~~
note: place parentheses around the assignment to silence this warning
while(c=fgetc(file)!='\n')
^
( )
answered Mar 21, 2014 at 12:52
Shafik YaghmourShafik Yaghmour
155k39 gold badges440 silver badges740 bronze badges
Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
- Remove From My Forums
-
Question
-
/* isspace example */ #include <stdio.h> #include <ctype.h> int main () { int c; int i=0; char str[]="Example sentence to test isspace\n"; while (str[i]) { c=int(str[i]); if (isspace(c)) c='\n'; putchar (c); i++; } return 0; }
isspace.c(11) : error C2059: syntax error : ‘type’
Could I ask that you post the correct code, please?
Answers
-
#include <stdio.h>
#include <locale.h>
int main(void)
{
struct lconv lc;
setlocale (LC_MONETARY,»»);
lc = *localeconv();
printf («Local Currency Symbol: %s\n»,lc.currency_symbol);
printf («International Currency Symbol: %s\n»,lc.int_curr_symbol);
return 0;
}
-
Marked as answer by
Monday, September 19, 2011 5:42 PM
-
Marked as answer by
-
>isspace.c(11) : error C2059: syntax error : ‘type’
Note that the problem in the first code example
is also due to an attempt to compile as C a
program which uses a feature of C++:c=int(str[i]);
This «function-style cast» is only valid in C++,
not in C. For C, change it to:c=(int)(str[i]);
or simply:
c=(int)str[i];
Your program is being compiled according to C language rules
because it has an extension of .c and that defaults to
building as C.— Wayne
-
Marked as answer by
brownie ri
Monday, September 19, 2011 5:42 PM
-
Marked as answer by
I’m attempting to translate a C++ DLL header file into a C/C++ compatible header. While I’ve gotten most of the major constructs in, I’m running into one last compiler issue I can’t seem to explain. The following code works fine in C++ but when I attempt to compile a C application which just includes this file I get errors for my function definitions in my header file.
Code.h:
typedef void *PVOID;
typedef PVOID HANDLE;
#define WINAPI __stdcall
#ifdef LIB_EXPORTS
#define LIB_API __declspec(dllexport)
#else
#define LIB_API __declspec(dllimport)
#endif
struct ToolState
{
HANDLE DriverHandle;
HANDLE Mutex;
int LockEnabled;
int Type;
};
#ifdef __cplusplus
extern "C" {
#endif
(LIB_API) int SetRate(ToolState *Driver, int rate);
(LIB_API) void EnableLock(ToolState *Driver) ;
(LIB_API) int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//These also give me the same error:
//LIB_API WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//__declspec(dllimport) WINAPI int SendPacket(ToolState *Driver, unsigned char *OutBuffer, int frameSize);
//Original C++ call that works fine with C++ but has multiple issues in C
//LIB_API int SetRate(ToolState *Driver, int rate);
#ifdef __cplusplus
}
#endif
Errors:
error C2059: syntax error : 'type'
error C2059: syntax error : 'type'
error C2059: syntax error : 'type'
Google searching hasn’t generated any relevant results. The following threads were close but don’t exactly answer my question:
C2059 syntax error using declspec macro for one function; compiles fine without it
http://support.microsoft.com/kb/117687/en-us
Why is this syntax error occuring?
Я просмотрел другие посты и, честно говоря, я до сих пор не уверен, что является причиной проблемы. Я программирую в Visual Studio и
У меня есть следующий код: (это главный C)
int main(int arc, char **argv) {
struct map mac_ip;
char line[MAX_LINE_LEN];
char *arp_cache = (char*) calloc(20, sizeof(char)); //yes i know the size is wrong - to be changed
char *mac_address = (char*) calloc(17, sizeof(char));
char *ip_address = (char*) calloc(15, sizeof(char));
arp_cache = exec("arp -a", arp_cache);
Он использует следующий код cpp:
#include "arp_piping.h"
extern "C" char *exec(char* cmd, char* arp_cache, FILE* pipe) {
pipe = _popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL) {
strcat(arp_cache, buffer);
}
}
_pclose(pipe);
return arp_cache;
}
С соответствующим заголовочным файлом:
#ifndef ARP_PIPING_H
#define ARP_PIPING_H
#endif
#ifdef __cplusplus
#define EXTERNC extern "C"#else
#define EXTERNC
#endif
#include <stdio.h>
#include <string.h>
extern "C" char *exec(char* cmd, char* arp_cache, FILE* pipe);
#undef EXTERNC
Но я продолжаю получать следующие ошибки:
1>d:\arp_proto\arp_proto\arp_piping.h(14): error C2059: syntax error : 'string'
1>main.c(22): warning C4013: 'exec' undefined; assuming extern returning int
1>main.c(22): warning C4047: '=' : 'char *' differs in levels of indirection from 'int'
Пожалуйста, могу ли я получить некоторую помощь, я смотрел на другие сообщения, касающиеся c2059, но до сих пор не получается
3
Решение
Измени свой exec
декларация об использовании EXTERNC
макрос, который вы постарались определить.
EXTERNC char *exec(char* cmd, char* arp_cache, FILE* pipe);
2
Другие решения
Я столкнулся с этой ошибкой компиляции при добавлении enum
к проекту. Оказалось, что одно из значений в enum
определение имело конфликт имени с препроцессором #define
,
enum
выглядело примерно так:
// my_header.h
enum Type
{
kUnknown,
kValue1,
kValue2
};
А потом в другом месте был #define
со следующим:
// ancient_header.h
#define kUnknown L"Unknown"
Затем в .cpp
где-то еще в проекте оба заголовка были включены:
// some_file.cpp
#include "ancient_header.h"#include "my_header.h"
// other code below...
Поскольку имя kUnknown
уже #define
когда компилятор пришел к kUnknown
символ в моем enum
, он сгенерировал ошибку, так как символ уже использовался для определения строки. Это вызвало загадку syntax error: 'string'
что я видел.
Это было невероятно запутанным, поскольку в enum
определение и компилируется просто отлично.
Это не помогло, что это было в очень большом проекте C ++, и что #define
был транзитивно включен в совершенно отдельный блок компиляции и был написан кем-то 15 лет назад.
Очевидно, что правильная вещь отсюда переименовать это ужасное #define
к чему-то менее распространенному, чем kUnknown
, но до тех пор, просто переименовав enum
значение для чего-то другого работает как фикс, например:
// my_header.h
enum Type
{
kSomeOtherSymbolThatIsntDefined,
kValue1,
kValue2
};
В любом случае, надеюсь, этот ответ будет полезен для кого-то еще, поскольку причина этой ошибки поставила меня в тупик на добрых полтора дня.
1
extern «C» используется для указания компилятору сделать его грамматикой языка Си, но вы имеете в виду объявить внешнюю функцию exec. Вы просто объединяетесь с этим. поэтому переписайте ваш код следующим образом в arp_piping.h:
/*extern "C"*/ char *exec(char* cmd, char* arp_cache, FILE* pipe);
и затем префикс extern «C» в файле cpp.
если вы хотите компилировать их с грамматикой C, просто установите в cpp вызов функции exec, поэтому напишите так:
extern "C" {
#include "arp_piping.h"}
0