Меню

Ошибка c2059 синтаксическая ошибка using namespace

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

BeyB

0 / 0 / 0

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

Сообщений: 23

1

28.10.2014, 17:52. Показов 4055. Ответов 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

Модератор

Эксперт С++

12627 / 10125 / 6097

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

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

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



  • 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

See more:











#include "stdafx.h"
#include "parser.h"
#include "HashTable.h"
#include "CountFrequency.h"

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
























void parser(string line, int fileNo, class HashTable & HT, frequencyList FL[])
{
        
        char * cStr, * cPtr;
        string tempString;

        
        
        cStr = new char [line.size() + 1];
        strcpy (cStr, line.c_str());

        
        cPtr = strtok (cStr, " ");
        while (cPtr != NULL)
        {
                if (strcmp(cPtr, "</TEXT>") != 0 && *cPtr != '.')
                {
                        tempString = string(cPtr);

                        
                        removeCommaBehind(tempString);

                        
                        removePeriodBehind(tempString);

                        
                        removePBehind(tempString);

                        
                        removePBefore(tempString);

                        
                        removeApsBehind(tempString);

                        
                        removeApBehind(tempString);

                        
                        removeIesBehind(tempString);

                        
                        removeSLBefore(tempString);

                        
                        removeEsBehind(tempString);

                        
                        removeSBehind(tempString);

                        
                        removeIngBehind(tempString);

                        
                        removeEdBehind(tempString);

                        
                        if(tempString.compare("a") != 0)
                        if(tempString.compare("an") != 0)
                        if(tempString.compare("any") != 0)
                        if(tempString.compare("all") != 0)
                        if(tempString.compare("and") != 0)
                        if(tempString.compare("are") != 0)
                        if(tempString.compare("at") != 0)
                        if(tempString.compare("as") != 0)
                        if(tempString.compare("b") != 0)
                        if(tempString.compare("be") != 0)
                        if(tempString.compare("been") != 0)
                        if(tempString.compare("but") != 0)
                        if(tempString.compare("by") != 0)
                        if(tempString.compare("c") != 0)
                        if(tempString.compare("ca") != 0)
                        if(tempString.compare("can") != 0)
                        if(tempString.compare("d") != 0)
                        if(tempString.compare("e") != 0)
                        if(tempString.compare("f") != 0)
                        if(tempString.compare("for") != 0)
                        if(tempString.compare("from") != 0)
                        if(tempString.compare("g") != 0)
                        if(tempString.compare("ga") != 0)
                        if(tempString.compare("h") != 0)
                        if(tempString.compare("ha") != 0)
                        if(tempString.compare("had") != 0)
                        if(tempString.compare("have") != 0)
                        if(tempString.compare("he") != 0)
                        if(tempString.compare("i") != 0)
                        if(tempString.compare("in") != 0)
                        if(tempString.compare("is") != 0)
                        if(tempString.compare("it") != 0)
                        if(tempString.compare("j") != 0)
                        if(tempString.compare("k") != 0)
                        if(tempString.compare("l") != 0)
                        if(tempString.compare("like") != 0)
                        if(tempString.compare("m") != 0)
                        if(tempString.compare("me") != 0)
                        if(tempString.compare("my") != 0)
                        if(tempString.compare("n") != 0)
                        if(tempString.compare("near") != 0)
                        if(tempString.compare("no") != 0)
                        if(tempString.compare("not") != 0)
                        if(tempString.compare("o") != 0)
                        if(tempString.compare("of") != 0)
                        if(tempString.compare("on") != 0)
                        if(tempString.compare("or") != 0)
                        if(tempString.compare("out") != 0)
                        if(tempString.compare("over") != 0)
                        if(tempString.compare("p") != 0)
                        if(tempString.compare("q") != 0)
                        if(tempString.compare("r") != 0)
                        if(tempString.compare("s") != 0)
                        if(tempString.compare("she") != 0)
                        if(tempString.compare("so") != 0)
                        if(tempString.compare("t") != 0)
                        if(tempString.compare("that") != 0)
                        if(tempString.compare("th") != 0)
                        if(tempString.compare("the") != 0)
                        if(tempString.compare("them") != 0)
                        if(tempString.compare("their") != 0)
                        if(tempString.compare("they") != 0)
                        if(tempString.compare("this") != 0)
                        if(tempString.compare("to") != 0)
                        if(tempString.compare("u") != 0)
                        if(tempString.compare("up") != 0)
                        if(tempString.compare("us") != 0)
                        if(tempString.compare("v") != 0)
                        if(tempString.compare("w") != 0)
                        if(tempString.compare("wa") != 0)
                        if(tempString.compare("was") != 0)
                        if(tempString.compare("we") != 0)
                        if(tempString.compare("were") != 0)
                        if(tempString.compare("which") != 0)
                        if(tempString.compare("who") != 0)
                        if(tempString.compare("will") != 0)
                        if(tempString.compare("with") != 0)
                        if(tempString.compare("x") != 0)
                        if(tempString.compare("y") != 0)
                        if(tempString.compare("z") != 0)
                        if(tempString.compare("") != 0)
                        if(tempString.compare("n") != 0)
                        if(tempString.compare(" ") != 0)
                        if(tempString.compare(" n") != 0)
                        if(tempString.compare("n") != 0)
                        if(tempString.compare(",") != 0)
                        if(tempString.compare(".") != 0)
                        if(tempString.compare("=") != 0)
                        {
                                
                                countFrequency(tempString, FL);
                        }
                }
                cPtr = strtok(NULL, "()/ ");
        }
        delete[] cStr;
}






void removeCommaBehind(string &tempString)
{
        if(tempString.find(",", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find(",", tempString.length() - 2), tempString.length(), "");
        }
}






void removePeriodBehind(string &tempString)
{
        if(tempString.find(".", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find(".", tempString.length() - 2), tempString.length(), "");
        }
}






void removeSLBefore(string &tempString)
{
        if(tempString[0] == '/')
                tempString.erase(0, 1);
}






void removeIesBehind(string &tempString)
{
        if(tempString.find("ies", tempString.length() - 3) < 35)
        {
                tempString.replace(tempString.find("ies", tempString.length() - 3), tempString.length(), "y");
        }
}






void removeEsBehind(string &tempString)
{
        if(tempString.find("sses", tempString.length() - 4) < 35)
        {
                tempString.replace(tempString.find("sses", tempString.length() - 4), tempString.length(), "ss");
        }
}






void removeSBehind(string &tempString)
{
        if(tempString.find("s", tempString.length() - 1) < 35)
        {
                tempString.replace(tempString.find("s", tempString.length() - 1), tempString.length(), "");
        }
}






void removeIngBehind(string &tempString)
{
        if(tempString.find("ing", tempString.length() - 3) < 35)
        {
                tempString.replace(tempString.find("ing", tempString.length() - 3), tempString.length(), "");
        }
}






void removeEdBehind(string &tempString)
{
        if(tempString.find("ed", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find("ed", tempString.length() - 2), tempString.length(), "");
        }
}






void removeApsBehind(string &tempString)
{
        if(tempString.find("'s", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find("'s", tempString.length() - 2), tempString.length(), "");
        }
}






void removeApBehind(string &tempString);
void removeApBehind(string &tempString)
{
        if(tempString.find("'", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find("'", tempString.length() - 2), tempString.length(), "");
        }
}






void removePBefore(string &tempString)
{
        if(tempString[0] == '(')
                tempString.erase(0, 1);
}






void removePBehind(string &tempString)
{
        if(tempString.find(")", tempString.length() - 2) < 35)
        {
                tempString.replace(tempString.find(")", tempString.length() - 2), tempString.length(), "");
        }
}



  • Forum
  • Beginners
  • Namespaces & «error C2059: syntax error

Namespaces & «error C2059: syntax error : ‘string'»

REPOSTED THE PROBLEM BELOW WITH ALL SUGGESTED IMPROVEMENTS. STILL PROBLEMS THOUGH!

THANKS GUYS

Last edited on

1
2
3
4
5
6
7
8
enum eLogEntryType
{
	LOG_GENERAL = 0,
	LOG_WARNING,
	LOG_DEBUG,
	LOG_ALL,
};

Remove the comma after LOG_ALL

LOG_ALL,

Thanks xandel33, but that hasn’t cleared up the problem. I changed my enum to

1
2
3
4
5
6
7
enum eLogEntryType
{
	LOG_GENERAL = 0,
	LOG_WARNING,
	LOG_DEBUG,
	LOG_ALL
};

But theres still the same error appearing on compile

Can you post the entire compile error?

Just as a matter of good programming practice, never use a namespace in a header file. You should remove the

from your header file and prefix everything that needs to be with std::.

OK, I’ve tried to tidy this up to make it a bit clearer. I’ve implemented the suggestions above, but still no luck. The error is caused by the member definition:

utilities::CLogFile m_Log(«global_log»,LOG_ALL,1);
//returns — error C2059: syntax error : ‘string’

Heres the header with the compiler error:

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
///////////////////////////////////////////////////////////////////////
// myConsoleApplication.h
///////////////////////////////////////////////////////////////////////

#pragma once

#include "CConsoleApplication.h"
#include "../Utilities/CLogFile.h"
#include "../Utilities/CTimer.h"

///////////////////////////////////////////////////////////////////////
// 
///////////////////////////////////////////////////////////////////////
class myConsoleApplication : public CConsoleApplication
{
	// add pre Main initialisation procedures
	DECLARE_INITIALISE;

	public:

		myConsoleApplication ();
		virtual ~myConsoleApplication ();	    
		virtual int Main (int iNumArgs, char** apcArgs);
		
	private:

		utilities::CLogFile m_Log("global_log",LOG_ALL,1);			
                //#######  - error C2059: syntax error : 'string'

		utilities::CTimer	 m_Timer;
};
///////////////////////////////////////////////////////////////////////

// implement the pre Main initialisation
REGISTER_INITIALISE(myConsoleApplication);

And heres a reduced class with zero functionality (but still the error)

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
46
47
48
///////////////////////////////////////////////////////////////////////
// CLogFile
///////////////////////////////////////////////////////////////////////

#pragma once

#include <list>
#include <string>
#include <fstream>
#include <ctime>

#include <cstdio>
#include <cstdarg>

// add to the utilities namespace
namespace utilities
{

///////////////////////////////////////////////////////////////////////

// types of valid log entry
enum eLogEntryType
{
	LOG_GENERAL = 0,
	LOG_WARNING,
	LOG_DEBUG,
	LOG_ALL
};


///////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////
class CLogFile
{
	///////////////////////////////////////////////////////////////////
	
	public:

		CLogFile(const char * csName, eLogEntryType eLogPolicy = LOG_ALL, unsigned int uiFlushSize = 30)
		{};
		
};
///////////////////////////////////////////////////////////////////////

} // close utilities namespace

/////////////////////////////////////////////////////////////////////// 

Is there a problem with my member defn?

Last edited on

You can’t initialize m_Log like that. You need to initialize it in the constructor:

1
2
3
4
myConsoleApplication ()
    :m_log("global_log",LOG_ALL,1);
....
utilities::CLogFile m_log;

I hope this helps! ^_^

rpgfan

Last edited on

Ahhhh ….. Initialization Lists(?) Never really used or paid any real attention to them in examples! Time to read up on them i think!

Thanks rpgfan and everyone else who offered advice. It’s appreciated!

Doug

Yep, initialization lists. Just beware of them when you play with virtual inheritance. They come back to bite you. 😉

Topic archived. No new replies allowed.

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка c7990 вызовите сервисный персонал kyocera
  • Ошибка c2011 timespec переопределение типа struct