Меню

Error c2059 синтаксическая ошибка строка

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Compiler Error C2059

Compiler Error C2059

03/26/2019

C2059

C2059

2be4eb39-3f37-4b32-8e8d-75835e07c78a

Compiler Error C2059

syntax error : ‘token’

The token caused a syntax error.

The following example generates an error message for the line that declares j.

// C2059e.cpp
// compile with: /c
// C2143 expected
// Error caused by the incorrect use of '*'.
   int j*; // C2059

To determine the cause of the error, examine not only the line that’s listed in the error message, but also the lines above it. If examining the lines yields no clue about the problem, try commenting out the line that’s listed in the error message and perhaps several lines above it.

If the error message occurs on a symbol that immediately follows a typedef variable, make sure that the variable is defined in the source code.

C2059 is raised when a preprocessor symbol name is re-used as an identifier. In the following example, the compiler sees DIGITS.ONE as the number 1, which is not valid as an enum element name:

#define ONE 1

enum class DIGITS {
    ZERO,
    ONE // error C2059
};

You may get C2059 if a symbol evaluates to nothing, as can occur when /Dsymbol= is used to compile.

// C2059a.cpp
// compile with: /DTEST=
#include <stdio.h>

int main() {
   #ifdef TEST
      printf_s("nTEST defined %d", TEST);   // C2059
   #else
      printf_s("nTEST not defined");
   #endif
}

Another case in which C2059 can occur is when you compile an application that specifies a structure in the default arguments for a function. The default value for an argument must be an expression. An initializer list—for example, one that used to initialize a structure—is not an expression. To resolve this problem, define a constructor to perform the required initialization.

The following example generates C2059:

// C2059b.cpp
// compile with: /c
struct ag_type {
   int a;
   float b;
   // Uncomment the following line to resolve.
   // ag_type(int aa, float bb) : a(aa), b(bb) {}
};

void func(ag_type arg = {5, 7.0});   // C2059
void func(ag_type arg = ag_type(5, 7.0));   // OK

C2059 can occur for an ill-formed cast.

The following sample generates C2059:

// C2059c.cpp
// compile with: /clr
using namespace System;
ref class From {};
ref class To : public From {};

int main() {
   From^ refbase = gcnew To();
   To^ refTo = safe_cast<To^>(From^);   // C2059
   To^ refTo2 = safe_cast<To^>(refbase);   // OK
}

C2059 can also occur if you attempt to create a namespace name that contains a period.

The following sample generates C2059:

// C2059d.cpp
// compile with: /c
namespace A.B {}   // C2059

// OK
namespace A  {
   namespace B {}
}

C2059 can occur when an operator that can qualify a name (::, ->, and .) must be followed by the keyword template, as shown in this example:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::Rebind<X>::Other AX; // error C2059
};

By default, C++ assumes that AY::Rebind isn’t a template; therefore, the following < is interpreted as a less-than sign. You must tell the compiler explicitly that Rebind is a template so that it can correctly parse the angle bracket. To correct this error, use the template keyword on the dependent type’s name, as shown here:

template <typename T> struct Allocator {
    template <typename U> struct Rebind {
        typedef Allocator<U> Other;
    };
};

template <typename X, typename AY> struct Container {
    typedef typename AY::template Rebind<X>::Other AX; // correct
};

Solved


When I try to compile this program i keep getting these errors:

(50) : error C2059: syntax error :
‘<=’

(50) : error C2143: syntax error
: missing ‘;’ before ‘{‘

(51) : error
C2059: syntax error : ‘>’

(51) : error
C2143: syntax error : missing ‘;’
before ‘{‘

(62) : error C2059: syntax
error : ‘else’

(62) : error C2143:
syntax error : missing ‘;’ before ‘{‘


#include <iostream>
#include <string>
#include <cassert>
using namespace std;

class income {
private:
    double incm;
    double subtract;
    double taxRate;
    double add;
    char status;
public:
    void setStatus ( char stats ) { status = stats; }
    void setIncm (double in ) { incm = in; }
    void setSubtract ( double sub ) { subtract = sub; }
    void setTaxRate ( double rate ) { taxRate = rate; }
    void setAdd ( double Add ) { add = Add; }

    char getStatus () { return status; }
    double getIncm () { return incm; }
    double getsubtract () { return subtract; }
    double getTaxRate () { return taxRate; }
    double getAdd () { return add; }
    void calcIncome ();
};

//calcIncome
int main () {
    income _new;
    double ajIncome = 0, _incm = 0;
    char status = ' ';
    bool done = false;
    while ( !done ) {
        cout << "Please enter your TAXABLE INCOME:n" << endl;
        cin >> _incm;
        if(cin.fail()) { cin.clear(); }
        if ( _incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
        if ( _incm > 0) { done = true; _new.setIncm(_incm); }
    }

    done = false;
    char stt [2] = " ";
    while ( !done ) {
        cout << "Please declare weather you are filing taxes jointly or single" << "n";
        cout << "t's' = singlent'm' = married" << endl;
        cin >> stt;
        if(cin.fail()) { cin.clear(); }
        if ( status == 's' || status == 'm' ) { done = true; _new.setStatus(stt[0]); }
        //if else { }
    }

    return 0;
};

This is part of a homework assignment so any pointers on bettering my programing would be **great**

Note:I am using Windows 7 with VS express C++ 2008

asked Jan 13, 2010 at 15:44

Wallter's user avatar

WallterWallter

4,2656 gold badges29 silver badges33 bronze badges

3

income is the name of your class. _incm is the name of your variable. Perhaps you meant this (notice the use of _incm not income):

if (_incm <= 0) { cout << "the income must be greater than 0... n" << endl; }
if (_incm > 0) { done = true; _new.setIncm(_incm); }

Frequently you use CamelCase for class names and lowercase for instance variable names. Since C++ is case-sensitive, they wouldn’t conflict each other if they use different case.

answered Jan 13, 2010 at 15:47

Jon-Eric's user avatar

Jon-EricJon-Eric

16.7k9 gold badges64 silver badges96 bronze badges

Your variable is named incom, not income. income refers to a type, so the compiler gets confused and you get a syntax error when you try to compare that type against a value in line 50.

One note for bettering you programming would be to use more distinct variable names to avoid such confusions… 😉

answered Jan 13, 2010 at 15:46

sth's user avatar

sthsth

218k53 gold badges277 silver badges364 bronze badges

1

  • Remove From My Forums
  • Question

  • struct A { int i; A() {} A(int i) : i(i) {} }; template <typename T> struct Help { typedef A B; }; template <typename T2> int foo(T2 t2, typename Help<T2>::B b = typename Help<T2>::B(0)) { return 0; } int main() { int I; int res = foo(I); return res; } /* $ cl.exe C2059.cpp Microsoft (R) C/C++ Optimizing Compiler Version 19.15.26729 for x64 Copyright (C) Microsoft Corporation. All rights reserved. C2059.cpp C2059.cpp(22): error C2059: syntax error: '' C2059.cpp(31): fatal error C1903: unable to recover from previous error(s); stopping compilation */

    • Edited by

      Thursday, September 20, 2018 1:00 PM
      add a line so that error message matches

I’ve got a DLL that I’ve created as a C++ Win32 application. To prevent name mangling in my DLL, I have used the EXPORT definition defined below:

#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif

EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);

To get this code to compile, I had to go into the project’s Properties and set the C/C++ Calling Convention to __stdcall (/Gz) and set Compile As to Compile as C++ Code (/TP).

This worked in Debug mode, but Release mode is throwing error C2059: syntax error: 'string' on all of my EXPORT functions — even though I have configured the Release mode settings to be the same as the Debug settings.

How do I get Release Mode to compile?

Regards,
~Joe
(Developing under Visual Studio 2008 Professional)

EDIT:
A lot of comments about my #define, which does not appear to be causing any problems.

To eliminate the confusion, my header file has been rewritten as follows:

#ifndef coilmodel_h
#define coilmodel_h

extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut);

#endif

That is all of it.

The error is:
Description error C2059: syntax error: 'string'
File coilmodel.h
Line 4

Again, this error only appears in Release mode, not Debug mode.
Project is a C++ Win32 DLL application.

I’ve got a DLL that I’ve created as a C++ Win32 application. To prevent name mangling in my DLL, I have used the EXPORT definition defined below:

#ifndef EXPORT
#define EXPORT extern "C" __declspec(dllexport)
#endif

EXPORT int _stdcall SteadyFor(double Par[], double Inlet[], double Outlet[]);

To get this code to compile, I had to go into the project’s Properties and set the C/C++ Calling Convention to __stdcall (/Gz) and set Compile As to Compile as C++ Code (/TP).

This worked in Debug mode, but Release mode is throwing error C2059: syntax error: 'string' on all of my EXPORT functions — even though I have configured the Release mode settings to be the same as the Debug settings.

How do I get Release Mode to compile?

Regards,
~Joe
(Developing under Visual Studio 2008 Professional)

EDIT:
A lot of comments about my #define, which does not appear to be causing any problems.

To eliminate the confusion, my header file has been rewritten as follows:

#ifndef coilmodel_h
#define coilmodel_h

extern "C" __declspec(dllexport) int _stdcall steadyFor(double Par[], double Inlet[], double Outlet[], char* FileIn, char* FileOut);

#endif

That is all of it.

The error is:
Description error C2059: syntax error: 'string'
File coilmodel.h
Line 4

Again, this error only appears in Release mode, not Debug mode.
Project is a C++ Win32 DLL application.

Я просмотрел другие посты и, честно говоря, я до сих пор не уверен, что является причиной проблемы. Я программирую в 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_protoarp_protoarp_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

BeyB

0 / 0 / 0

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

Сообщений: 23

1

28.10.2014, 17:52. Показов 4028. Ответов 8

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


У меня проблема в этом коде , подскажите пожалуйста что нужно исправлять

вот сам код

C++
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
#include <iostream>
#include <cmath>
#include <conio.h>
 
using namespace std;
int main()
 
{
    //Declare Variables
    double x, x1, x2, a, b, c;
 
    cout << "Input values of a, b, and c.";
    cin >> a >> b >> c;
 
    for (int i = 1; i <= 10; ++i);
    {
        if ((b * b - 4 * a * c) > 0)
            cout << "x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)" &&
            cout << "x2 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a)";
 
        if else ((b * b - 4 * a * c) = 0)
            cout << "x = ((-b + sqrt(b * b - 4 * a * c)) / (2 * a)"
 
            if else ((b * b - 4 * a * c) < 0)
                cout << "x1 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)" &&
                cout << "x2 = ((-b + sqrt(b * b - 4 * a * c) * sqrt (-1)) / (2 * a)";
 
        _getch();
 
    }
 
 
    return (0);
 
}

а вот ошибка

1>—— Сборка начата: проект: Проект3, Конфигурация: Debug Win32 ——
1> Исходный код.cpp
1>c:userspc hackerdocumentsvisual studio 2013projectsпроект3проект3исходный код.cpp(21): error C2059: синтаксическая ошибка: else
========== Сборка: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

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



0



Вездепух

Эксперт CЭксперт С++

10420 / 5692 / 1550

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

Сообщений: 14,018

28.10.2014, 17:59

2

Что такое ‘if else’??? Это бессмысленная белиберда.

Очевидно имелось в виду ‘else if’…

Отдельно стоит заметить, что скорее всего от вас ожидали, что вы напечатаете сами решения квадратного уравнения, а не формулы для решения из учебника.

P.S. Ваша манера объединять последовательные выводы в ‘cout’ через оператор ‘&&’ остроумна, но вызывает удивление в коде у автора, который путает ‘if else’ с ‘esle if’.



0



5 / 5 / 5

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

Сообщений: 463

28.10.2014, 18:01

3

Что-то у вас тут не то. Во первых я вижу,что пропущена точка с запятой в 22 строке. Ну и если вы хотите,чтобы формулы записанные в cout работали,то их не нужно брать в кавычки.

Добавлено через 25 секунд
И надо писать else if



0



0 / 0 / 0

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

Сообщений: 23

28.10.2014, 18:12

 [ТС]

4

спасибо за помощь но я совсем уже запутался, мне надо собрать прогу которая должен решить дискриминант , а у мя Бог знает что получился , может поможете , обясните что к чему ?



0



Вероника99

5 / 5 / 5

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

Сообщений: 463

28.10.2014, 18:43

5

Прогу не компилировала,но вроде ничего не упустила. Там стоит обратить внимание на то,что корень вычисляется только с неотрицательных чисел

C++
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
#include <cmath>
#include <conio.h>
 
using namespace std;
int main()
 
{
    //Declare Variables
    double x=0, x1=0, x2=0, a, b, c;
 
    cout << "Input values of a, b, and c.";
    cin >> a >> b >> c;
 
    
        if ((b * b - 4 * a * c) > 0)
      {      x1=x2=(-b + sqrt((float)(b * b - 4 * a * c))) / (2 * a);
      cout<<" "<<x1<<x2<<endl;
 
        }
 
     else if((b * b - 4 * a * c) == 0)
 {            x=(-b + sqrt(abs((b * b - 4.0 * a * c)))) / (2 * a);
         cout<<" "<<x<<endl;
        }
         else if ((b * b - 4 * a * c) < 0)
            {   x1=x2=(-b + sqrt(abs((float)(b * b - 4 * a * c)))) * sqrt (abs((-1.0) / (2 * a)));
      cout<<" "<<x1<<endl;
    
     }
    
 
    return (0);
 
}



1



73 / 73 / 28

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

Сообщений: 309

28.10.2014, 18:45

6

Цитата
Сообщение от Вероника99
Посмотреть сообщение

Прогу не компилировала

оно и видно) для cin и cout нужна iostream, которой нет)



0



5 / 5 / 5

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

Сообщений: 463

28.10.2014, 18:46

7

О да,самое главное)))



0



BeyB

0 / 0 / 0

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

Сообщений: 23

28.10.2014, 19:03

 [ТС]

8

спасибо успел сделать всё кажется пол часа назад , спасибо большое за то что предупредили что мой первый код было магко говоря бесполезным

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
    int x, y, s;
    cin >> x;
    cin >> y;
    s = x + y;
        cout << s;
        
        _getch();
 
        return 0;
 
}



0



zss

Модератор

Эксперт С++

12623 / 10122 / 6096

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

Сообщений: 27,154

28.10.2014, 19:09

9

Лучший ответ Сообщение было отмечено BeyB как решение

Решение

C++
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
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
    cout << "Input values of a, b, and c.";
    double a, b, c;
    cin >> a >> b >> c;
     if(a==0)
    {
         if(b!=0)
         {
                double x=-c/b;
                cout<<" "<<x<<endl;
         }else
                cout<<" No solutionn";
        return 0;
    }
 
    double D=b * b - 4 * a * c;
    if (D>0)
    {     
         double x1=(-b + sqrt(D)) / (2. * a);
         double x2=(-b - sqrt(D)) / (2. * a);
         cout<<" "<<x1<<" "<<x2<<endl;
    }else 
    if(D == 0)
    {            
          x= -b / (2 * a);
          cout<<" "<<x<<endl;
    }else
          cout<<" No solutionn";
    return 0;    
}



1



Problem

The Microsoft C/C++ compiler might throw this error, when the code contains an IBM Rational Test RealTime Code Review pragma. This technote proposes a workaround.

Symptom

The error message is as follows:

error C2059: syntax error : 'bad suffix on number'

Cause

See the following code.


#pragma attol crc_justify (Rule M1.1w, "Rule M1.1w : This rule is acceptable on the next line")

The Microsoft Visual C/C++ compiler reports the error on this line.

The Microsoft Visual C/C++ compiler interprets the first parameter of the

crc_justify

pragma,

Rule M1.1w

, as a number. However the suffix

w

is not an allowed suffix for a number. This is not a defect in the implementation of the pragmas. The ANSI C standard states, that compilers should ignore pragmas, that they do not understand.

Resolving The Problem

To workaround the problem you use the alternate name of the rule as the first parameter to the crc_justify pragma.

Open your project’s

confrule.xml

file in a text editor. You can find the path to this file in the settings dialog box, section Code Review > Rule Configuration.
If you see the string default, open the file in the IBM Rational Test RealTime installation directory. For example:

C:Program FilesRationalTestRealTimepluginsCommonlibconfrule.xml

In this file you see the following line near the beginning:

<rule name=»CRC_10_11″ label=»Rule M1.1w» severity=»2″ repeat=»0″ errMsg=»ANSI C warning: %name%» />

The n

ame

attribute gives the internal name for the rule. The

label

attribute gives the external name for the rule. You can use either the internal or the external name in the

crc_justify

pragma.

Therefore to workaround this problem, you change your pragma to become:

#pragma attol crc_justify (CRC_10_11, "Rule M1.1w : This rule is acceptable on the next line")

[{«Product»:{«code»:»SSSHUF»,»label»:»Rational Test RealTime»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Code Review for C»,»Platform»:[{«code»:»PF002″,»label»:»AIX»},{«code»:»PF010″,»label»:»HP-UX»},{«code»:»PF016″,»label»:»Linux»},{«code»:»PF027″,»label»:»Solaris»},{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.0;7.0.0.1;7.0.5;7.0.5.1;7.5″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]

Product Synonym

testrt;rtrt

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Error at loading of ippcv library photoshop 2021 решение ошибки
  • Error archive data corrupted unarc dll вернул код ошибки 5 не хватает памяти