Синтаксическая ошибка идентификатор tchar

Can’t understand why I’m getting this error? im kinda new to c++ and microsoft visual studio, kinda lost on this. Thanks for the help on advance.

#include <iostream>                          
#include <fstream>                           
#include <string>                       
#include <windows.h>                        

using namespace std;
#define STILL_PLAYING   1
#define QUIT            0
#define GAME_FILE "Mundo.txt";

////// the main class of the game, its a room, ull be moving around to other rooms. /////////////
struct posicao{
    string posAtual;
    string Descricao;
    string posNorte;
    string posSul;
    string posLeste;
    string posOeste;
};

/////////// displays the room that you are at the moment /////
void mostraposicao(posicao &posicao)
{
    cout << posicao.Descricao << endl << endl;
}

////////// gets all info of the present room ////
void getPosicaoInfo(posicao &posicao, ifstream fin) {
    string strLine = "";
    string strTemp = "";

    string strPosicao = "<" + posicao.posAtual + ">";
    fin.seekg(NULL, ios::beg);
    fin.clear();

    // reads the txt file line by line till it reaches '*' because
    // the room description is in this format --->> "text '*'"
    // to identify the end of the description.
    while (getline(fin, strLine, '\n')) {
        if (strLine == strPosicao) {
            getline(fin, posicao.Descricao, '*');
            fin >> strTemp >> posicao.posNorte;
            fin >> strTemp >> posicao.posSul;
            fin >> strTemp >> posicao.posLeste;
            fin >> strTemp >> posicao.posOeste;
            return;
        }
    }
}

//// moves to another room////////
void Andar(ifstream fin, posicao &posicao, string strPosicao) {
    if (string == "None") {
        cout << "Você não pode ir por ai!!!" << endl;
        return;
    }
    posicao.posAtual = strPosicao;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);
}

//////////get the input of the player ///////////
int getComando(ifstream fin, posicao &posicao) {
    string strComando = "";
    cout <<endl << ":";
    cin >> strComando;
    if (strComando == "Olhar") {
        mostraposicao(posicao);
    }
    else if(strComando == "Norte") {
        Andar(fin, posicao, posicao.posNorte);
    }
    else if (strComando == "Sul") {
        Andar(fin, posicao, posicao.posSul);
    }
    else if (strComando == "Leste") {
        Andar(fin, posicao, posicao.posLeste);
    }
    else if (strComando == "Oeste") {
        Andar(fin,posicao,posicao.posOeste)
    }
    else if (strComando == "Sair") {
        cout << "Você já desistiu?" << endl;
        return QUIT;
    }
    else if (strComando == "Ajuda" || strComando == "?") {
        cout << endl << "Os comandos do jogo sao : Olhar, Norte, Sul, Leste,Oeste,Sair,Ajuda" << endl;
    }
    else {
        cout << "Ahñ???" << endl;
    }
    return STILL_PLAYNG;
}

///// where the game begins //////////
int _tmain(int argc, _TCHAR* argv[])
{
    ifstream fin;    /// creates the stream file ///
    posicao posicao;   //// the room that will be used in the game ///
    fin.open(GAME_FILE);   ///// gets the text file////
    if (fin.fail())   /////// if the text doesnt exist, the game ends ////
    {
        // Display a error message and return -1 (Quit the program)
        cout << "Jogo não encontrado" << endl;
        return -1;
    }
    // reads twice, so it skips the <start> and reads the <middle>
    // (first room ull be in the game
    fin >> posicao.posAtual >> posicao.posAtual;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);

    /////// if the input its quit, ends the game//////
    while (1) {
        if (getComando(fin, posicao) == QUIT)
            break;
    }
    /////// closes the txt file, ends the game//////////
    fin.close();
    Sleep(3000); /// delays  the close///
    return 0;
}

the text is in this format:

<Start> Middle

<Middle>
You step into a house where you are nearly
blinded by the light shinning through the window.
You have been searching for your friend who was captured.
The trail has led you to this mansion.
There is a door in every direction.*
<north> Top
<east>  Right
<south> Bottom
<west>  Left

<Left>
There is a fountain in the middle of this room.
The cool, crisp air swirls about and encircles you.
There is only one door to the east where you came.*
<north> None
<east>  Middle
<south> None
<west>  None

<Bottom>
You step back outside of the mansion and grab some fresh air.
It is quite refreshing, comapred to the damp smell from within.
You here rustling from the second story of the house.  It could be your friend.
Your only option is to go back inside and get them out of here!*
<north> Middle
<east>  None
<south> None
<west>  None

<Right>
As you pass through the door you feel a chill run
down your spine.  It appears that there something or 
someone or something sitting in the corner, covered by darkness.
There is no where to go but back to the west.*
<north> None
<east>  None
<south> None
<west>  Middle

<Top>
As you get closer to the second story of the mansion, the sounds of someone
struggling can be heard more distinctly.  There is no turning back now.
One door is to the south and one is to the north up a stairwell.*
<north> End
<east>  None
<south> Middle
<west>  None

<End>
You find your friend tied to a chair.  Their hands, feet and mouth are bound,
but it's as if their eyes are screaming at you.  Short bursts of muffled yells
are heard from under the cloth that holds their mouth, as if to say, "Run!".  
What could they be trying to say?  As you walk closer to them they seem to get 
louder and more depserate. That's when you see it.  It had been lurching in the
corner, feathered by darkness.   To be continued...*
<north> None
<east>  None
<south> None
<west>  None

aprkaer

0 / 0 / 0

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

Сообщений: 9

1

19.05.2013, 12:44. Показов 17848. Ответов 19

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


Студворк — интернет-сервис помощи студентам

Программа по обходу в глубину графа. вылетает error C2061: синтаксическая ошибка: идентификатор «_TCHAR».
что с этим делать?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 2w3.cpp: главный файл проекта.
 
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
#include <windows.h>
using namespace System;
using namespace std;
 
vector<vector<int>> Mat;
vector<int> Vec;
vector<char> used;
void dfs (int v) {
    used[v] = true;
    for (int i=0; Mat.size(); ++i)
        if (!used[i])
            dfs (i);
}
 
/////////////////////////Функция русификации////////////////////////////
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}
int main(int argc, _TCHAR* argv[]){
 
    cout<<Rus("Введите количество вершин:");
    int nCount,i=0;
    cin>>nCount;
    while(i!=nCount){
        cout<<Rus("Введите строку списка, если захотите закончить ввод нажмите -1:")<<endl;
        int op;
        for(int j=0;;++j){
            cin>>op;
            if(op!=-1){Vec.push_back(op);}
            else {break;}
        }
        Mat.push_back(Vec);
        Vec.clear();
        ++i;
    }
    cout<<Rus("Введите вершину, с которой вы хотите построить пвг:");
    int v;
    cin>>v;
    dfs(v);
    
    return 0;
}



0



5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 12:56

2

Цитата
Сообщение от aprkaer
Посмотреть сообщение

что с этим делать?

Заменить на char.



0



0 / 0 / 0

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

Сообщений: 9

19.05.2013, 14:19

 [ТС]

3

ха-ха. если б всё так просто.



0



alsav22

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 14:29

4

Какой вопрос — такой и ответ. Вставляю ваш код в студию, заменяю, и компиляция без ошибок.

Добавлено через 6 минут
Ещё вариант:

C++
1
#include <tchar.h>



0



Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:34

5

Цитата
Сообщение от aprkaer
Посмотреть сообщение

int main(int argc, _TCHAR* argv[])

может просто написать?

C++
1
int main()



0



alsav22

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 14:37

6

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

может просто написать?

C++
1
int main()

Я так понял, что ТС нужно использовать _TCHAR.



0



Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:42

7

Цитата
Сообщение от alsav22
Посмотреть сообщение

Я так понял, что ТС нужно использовать _TCHAR.

но ведь он как и

C++
1
using namespace System;

в программе нигде не используется.



0



Croessmah

19.05.2013, 14:43

 

#8

Не по теме:

alsav22, не думаю что ему нужен TCHAR:

C++
1
2
3
4
5
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}



0



alsav22

19.05.2013, 14:50

Не по теме:

Тогда я не понимаю его третий пост.



0



Issues

19.05.2013, 14:54

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

Тогда я не понимаю его третий пост.

скорее всего он вставляет этот код в простой «Win32 Console Application»



0



alsav22

19.05.2013, 14:59

Не по теме:

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

Не по теме:

скорее всего он вставляет этот код в простой «Win32 Console Application»

И что, в нём нельзя заменить _TCHAR на char?



0



Issues

19.05.2013, 15:02

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

И что, в нём нельзя заменить _TCHAR на char?

можно. :D



0



Croessmah

19.05.2013, 15:04

Не по теме:

Да что мы гадаем…нам за это не платят — зайдет пояснит :)



0



0 / 0 / 0

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

Сообщений: 9

19.05.2013, 21:32

 [ТС]

14

TCAR на char не канает, оибки и добавление #include char тоже.



0



5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 23:34

15

Не по теме:

Цитата
Сообщение от Croessmah
Посмотреть сообщение

Да что мы гадаем…нам за это не платят — зайдет пояснит

Пояснил, называется…

Цитата
Сообщение от aprkaer
Посмотреть сообщение

и добавление #include char тоже

А #include <tchar.h> ? Что за среда? Проект?



0



0 / 0 / 0

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

Сообщений: 9

19.05.2013, 23:59

 [ТС]

16

CLR console application/ visual studio 2010



0



Неэпический

17848 / 10616 / 2049

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

Сообщений: 26,686

Записей в блоге: 1

20.05.2013, 00:12

17

C++ и C++/CLI разные языки.



0



5496 / 4891 / 831

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

Сообщений: 13,587

20.05.2013, 00:13

18

Цитата
Сообщение от aprkaer
Посмотреть сообщение

TCAR на char не канает, ошибки

Ошибки какие?



0



0 / 0 / 0

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

Сообщений: 9

20.05.2013, 00:27

 [ТС]

19

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Добавлено через 1 минуту
Пришли пожалуйста EXE-шник, если компилится. zelenyy81@mail.ru



0



5496 / 4891 / 831

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

Сообщений: 13,587

20.05.2013, 01:07

20

Цитата
Сообщение от aprkaer
Посмотреть сообщение

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Если заменить _TCAR на char? Откуда там такая ошибка может взяться, если _TCHAR уже нет?

Добавлено через 12 минут
Ошибки там другие появляются, компоновщик выдаёт:

1>—— Построение начато: проект: CLR3Cons, Конфигурация: Debug Win32 ——
1> CLR3Cons.cpp
1>CLR3Cons.obj : error LNK2028: ссылка на неразрешенную лексему (0A000408) «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>CLR3Cons.obj : error LNK2019: ссылка на неразрешенный внешний символ «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>D:\MY C++Projects\CLR3Cons\Debug\CLR3Cons.exe : fatal error LNK1120: 2 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Не находит реализацию для CharToOemA()?

Добавлено через 7 минут

Цитата
Сообщение от aprkaer
Посмотреть сообщение

Пришли пожалуйста EXE-шник, если компилится.

Тут всё дело в пректе. Компилится без проблем, если проект не CLR.



0



Can’t understand why I’m getting this error? im kinda new to c++ and microsoft visual studio, kinda lost on this. Thanks for the help on advance.

#include <iostream>                          
#include <fstream>                           
#include <string>                       
#include <windows.h>                        

using namespace std;
#define STILL_PLAYING   1
#define QUIT            0
#define GAME_FILE "Mundo.txt";

////// the main class of the game, its a room, ull be moving around to other rooms. /////////////
struct posicao{
    string posAtual;
    string Descricao;
    string posNorte;
    string posSul;
    string posLeste;
    string posOeste;
};

/////////// displays the room that you are at the moment /////
void mostraposicao(posicao &posicao)
{
    cout << posicao.Descricao << endl << endl;
}

////////// gets all info of the present room ////
void getPosicaoInfo(posicao &posicao, ifstream fin) {
    string strLine = "";
    string strTemp = "";

    string strPosicao = "<" + posicao.posAtual + ">";
    fin.seekg(NULL, ios::beg);
    fin.clear();

    // reads the txt file line by line till it reaches '*' because
    // the room description is in this format --->> "text '*'"
    // to identify the end of the description.
    while (getline(fin, strLine, 'n')) {
        if (strLine == strPosicao) {
            getline(fin, posicao.Descricao, '*');
            fin >> strTemp >> posicao.posNorte;
            fin >> strTemp >> posicao.posSul;
            fin >> strTemp >> posicao.posLeste;
            fin >> strTemp >> posicao.posOeste;
            return;
        }
    }
}

//// moves to another room////////
void Andar(ifstream fin, posicao &posicao, string strPosicao) {
    if (string == "None") {
        cout << "Você não pode ir por ai!!!" << endl;
        return;
    }
    posicao.posAtual = strPosicao;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);
}

//////////get the input of the player ///////////
int getComando(ifstream fin, posicao &posicao) {
    string strComando = "";
    cout <<endl << ":";
    cin >> strComando;
    if (strComando == "Olhar") {
        mostraposicao(posicao);
    }
    else if(strComando == "Norte") {
        Andar(fin, posicao, posicao.posNorte);
    }
    else if (strComando == "Sul") {
        Andar(fin, posicao, posicao.posSul);
    }
    else if (strComando == "Leste") {
        Andar(fin, posicao, posicao.posLeste);
    }
    else if (strComando == "Oeste") {
        Andar(fin,posicao,posicao.posOeste)
    }
    else if (strComando == "Sair") {
        cout << "Você já desistiu?" << endl;
        return QUIT;
    }
    else if (strComando == "Ajuda" || strComando == "?") {
        cout << endl << "Os comandos do jogo sao : Olhar, Norte, Sul, Leste,Oeste,Sair,Ajuda" << endl;
    }
    else {
        cout << "Ahñ???" << endl;
    }
    return STILL_PLAYNG;
}

///// where the game begins //////////
int _tmain(int argc, _TCHAR* argv[])
{
    ifstream fin;    /// creates the stream file ///
    posicao posicao;   //// the room that will be used in the game ///
    fin.open(GAME_FILE);   ///// gets the text file////
    if (fin.fail())   /////// if the text doesnt exist, the game ends ////
    {
        // Display a error message and return -1 (Quit the program)
        cout << "Jogo não encontrado" << endl;
        return -1;
    }
    // reads twice, so it skips the <start> and reads the <middle>
    // (first room ull be in the game
    fin >> posicao.posAtual >> posicao.posAtual;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);

    /////// if the input its quit, ends the game//////
    while (1) {
        if (getComando(fin, posicao) == QUIT)
            break;
    }
    /////// closes the txt file, ends the game//////////
    fin.close();
    Sleep(3000); /// delays  the close///
    return 0;
}

the text is in this format:

<Start> Middle

<Middle>
You step into a house where you are nearly
blinded by the light shinning through the window.
You have been searching for your friend who was captured.
The trail has led you to this mansion.
There is a door in every direction.*
<north> Top
<east>  Right
<south> Bottom
<west>  Left

<Left>
There is a fountain in the middle of this room.
The cool, crisp air swirls about and encircles you.
There is only one door to the east where you came.*
<north> None
<east>  Middle
<south> None
<west>  None

<Bottom>
You step back outside of the mansion and grab some fresh air.
It is quite refreshing, comapred to the damp smell from within.
You here rustling from the second story of the house.  It could be your friend.
Your only option is to go back inside and get them out of here!*
<north> Middle
<east>  None
<south> None
<west>  None

<Right>
As you pass through the door you feel a chill run
down your spine.  It appears that there something or 
someone or something sitting in the corner, covered by darkness.
There is no where to go but back to the west.*
<north> None
<east>  None
<south> None
<west>  Middle

<Top>
As you get closer to the second story of the mansion, the sounds of someone
struggling can be heard more distinctly.  There is no turning back now.
One door is to the south and one is to the north up a stairwell.*
<north> End
<east>  None
<south> Middle
<west>  None

<End>
You find your friend tied to a chair.  Their hands, feet and mouth are bound,
but it's as if their eyes are screaming at you.  Short bursts of muffled yells
are heard from under the cloth that holds their mouth, as if to say, "Run!".  
What could they be trying to say?  As you walk closer to them they seem to get 
louder and more depserate. That's when you see it.  It had been lurching in the
corner, feathered by darkness.   To be continued...*
<north> None
<east>  None
<south> None
<west>  None

aprkaer

0 / 0 / 0

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

Сообщений: 9

1

19.05.2013, 12:44. Показов 17768. Ответов 19

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


Студворк — интернет-сервис помощи студентам

Программа по обходу в глубину графа. вылетает error C2061: синтаксическая ошибка: идентификатор «_TCHAR».
что с этим делать?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 2w3.cpp: главный файл проекта.
 
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
#include <windows.h>
using namespace System;
using namespace std;
 
vector<vector<int>> Mat;
vector<int> Vec;
vector<char> used;
void dfs (int v) {
    used[v] = true;
    for (int i=0; Mat.size(); ++i)
        if (!used[i])
            dfs (i);
}
 
/////////////////////////Функция русификации////////////////////////////
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}
int main(int argc, _TCHAR* argv[]){
 
    cout<<Rus("Введите количество вершин:");
    int nCount,i=0;
    cin>>nCount;
    while(i!=nCount){
        cout<<Rus("Введите строку списка, если захотите закончить ввод нажмите -1:")<<endl;
        int op;
        for(int j=0;;++j){
            cin>>op;
            if(op!=-1){Vec.push_back(op);}
            else {break;}
        }
        Mat.push_back(Vec);
        Vec.clear();
        ++i;
    }
    cout<<Rus("Введите вершину, с которой вы хотите построить пвг:");
    int v;
    cin>>v;
    dfs(v);
    
    return 0;
}

0

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 12:56

2

Цитата
Сообщение от aprkaer
Посмотреть сообщение

что с этим делать?

Заменить на char.

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 14:19

 [ТС]

3

ха-ха. если б всё так просто.

0

alsav22

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 14:29

4

Какой вопрос — такой и ответ. Вставляю ваш код в студию, заменяю, и компиляция без ошибок.

Добавлено через 6 минут
Ещё вариант:

C++
1
#include <tchar.h>

0

Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:34

5

Цитата
Сообщение от aprkaer
Посмотреть сообщение

int main(int argc, _TCHAR* argv[])

может просто написать?

C++
1
int main()

0

alsav22

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 14:37

6

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

может просто написать?

C++
1
int main()

Я так понял, что ТС нужно использовать _TCHAR.

0

Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:42

7

Цитата
Сообщение от alsav22
Посмотреть сообщение

Я так понял, что ТС нужно использовать _TCHAR.

но ведь он как и

C++
1
using namespace System;

в программе нигде не используется.

0

Croessmah

19.05.2013, 14:43

#8

Не по теме:

alsav22, не думаю что ему нужен TCHAR:

C++
1
2
3
4
5
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}

0

alsav22

19.05.2013, 14:50

Не по теме:

Тогда я не понимаю его третий пост.

0

Issues

19.05.2013, 14:54

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

Тогда я не понимаю его третий пост.

скорее всего он вставляет этот код в простой «Win32 Console Application»

0

alsav22

19.05.2013, 14:59

Не по теме:

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

Не по теме:

скорее всего он вставляет этот код в простой «Win32 Console Application»

И что, в нём нельзя заменить _TCHAR на char?

0

Issues

19.05.2013, 15:02

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

И что, в нём нельзя заменить _TCHAR на char?

можно. :D

0

Croessmah

19.05.2013, 15:04

Не по теме:

Да что мы гадаем…нам за это не платят — зайдет пояснит :)

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 21:32

 [ТС]

14

TCAR на char не канает, оибки и добавление #include char тоже.

0

5496 / 4891 / 831

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

Сообщений: 13,587

19.05.2013, 23:34

15

Не по теме:

Цитата
Сообщение от Croessmah
Посмотреть сообщение

Да что мы гадаем…нам за это не платят — зайдет пояснит

Пояснил, называется…

Цитата
Сообщение от aprkaer
Посмотреть сообщение

и добавление #include char тоже

А #include <tchar.h> ? Что за среда? Проект?

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 23:59

 [ТС]

16

CLR console application/ visual studio 2010

0

Неэпический

17819 / 10592 / 2044

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

Сообщений: 26,636

Записей в блоге: 1

20.05.2013, 00:12

17

C++ и C++/CLI разные языки.

0

5496 / 4891 / 831

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

Сообщений: 13,587

20.05.2013, 00:13

18

Цитата
Сообщение от aprkaer
Посмотреть сообщение

TCAR на char не канает, ошибки

Ошибки какие?

0

0 / 0 / 0

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

Сообщений: 9

20.05.2013, 00:27

 [ТС]

19

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Добавлено через 1 минуту
Пришли пожалуйста EXE-шник, если компилится. zelenyy81@mail.ru

0

5496 / 4891 / 831

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

Сообщений: 13,587

20.05.2013, 01:07

20

Цитата
Сообщение от aprkaer
Посмотреть сообщение

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Если заменить _TCAR на char? Откуда там такая ошибка может взяться, если _TCHAR уже нет?

Добавлено через 12 минут
Ошибки там другие появляются, компоновщик выдаёт:

1>—— Построение начато: проект: CLR3Cons, Конфигурация: Debug Win32 ——
1> CLR3Cons.cpp
1>CLR3Cons.obj : error LNK2028: ссылка на неразрешенную лексему (0A000408) «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>CLR3Cons.obj : error LNK2019: ссылка на неразрешенный внешний символ «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>D:MY C++ProjectsCLR3ConsDebugCLR3Cons.exe : fatal error LNK1120: 2 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Не находит реализацию для CharToOemA()?

Добавлено через 7 минут

Цитата
Сообщение от aprkaer
Посмотреть сообщение

Пришли пожалуйста EXE-шник, если компилится.

Тут всё дело в пректе. Компилится без проблем, если проект не CLR.

0

Прошу не убивать и не крыть матом, снова с проблемами…

Имеется следующий код, который выводит программно ярлык из папки «сетевые подключения». 

#include <stdio.h>
#include <shlobj.h>
#include <shlwapi.h>

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow);
int short_cut_startup(char *connection_name, LPWSTR link_name);
LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl);
UINT GetSize(LPCITEMIDLIST pidl);
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd);

LPMALLOC pMalloc;

int main(void)
{
    if(short_cut_startup("demo", L"demo.lnk"))
        printf("Success!n");
    else printf("Can't create shortcut!n");
    return 0;
}

/* Main function which creating shortcut on desktop */
int short_cut_startup(char *connection_name, LPWSTR link_name)
{
    LPITEMIDLIST pidConnections = NULL;
    LPITEMIDLIST pidlItems = NULL;
    LPITEMIDLIST pidlDesk = NULL;
    IShellFolder *psfFirstFolder = NULL;
    IShellFolder *psfDeskTop = NULL;
    IShellFolder *pConnections = NULL;
    LPENUMIDLIST ppenum = NULL;
    ULONG celtFetched;
    HRESULT hr;
    STRRET str_curr_connection_name;
    TCHAR curr_connection_name[MAX_PATH] = "";    /* Connection point name */
    TCHAR desktop_path[MAX_PATH]="";            /* Path to desktop */
    TCHAR full_link_name[MAX_PATH]="";            /* Full shortcut name */
    LPITEMIDLIST full_pid;                        /* Full shortcut pid */

   
    CoInitialize( NULL );
    /* Allocating memory for Namespace objects */
    hr = SHGetMalloc(&pMalloc);
    hr = SHGetFolderLocation(NULL, CSIDL_CONNECTIONS, NULL, NULL, &pidConnections);

    /* Get full path to desktop */
    SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);

    hr = SHGetDesktopFolder(&psfDeskTop);
    hr = psfDeskTop->BindToObject(pidConnections, NULL, IID_IShellFolder, (LPVOID *) &pConnections);
    hr = pConnections->EnumObjects(NULL,SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &ppenum);

    /* Loop for searching our connection */
    while(hr = ppenum->Next(1,&pidlItems, &celtFetched) == S_OK && (celtFetched) == 1)
    {
        pConnections->GetDisplayNameOf(pidlItems, SHGDN_INFOLDER, &str_curr_connection_name);
        StrRetToBuf(&str_curr_connection_name, pidlItems, curr_connection_name, MAX_PATH);
        if(!strcmp(curr_connection_name,connection_name))
            goto found;
    }
    printf("Connection not found in "Network connections" folder.n");
    return 0;
found:
    /* Append PIDLs */
    full_pid=Append(pidConnections,pidlItems);
    SetCurrentDirectory(desktop_path);
    if(!CreateShortCut(link_name, full_pid, "C:windows", 0, SW_SHOWNORMAL))
        return 0;

    ppenum->Release();
    pMalloc->Free(pidlItems);
    pMalloc->Free(pidConnections);
    pMalloc->Release();
    pConnections->Release();
    CoUninitialize();
    return 1;
}

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow)
{ 
    IShellLink * pSL; 
    IPersistFile * pPF; 
    HRESULT hRes; 
    hRes = CoCreateInstance(CLSID_ShellLink, 0,CLSCTX_INPROC_SERVER, 
                            IID_IShellLink, (LPVOID *)&pSL); 
    if( SUCCEEDED(hRes) ) 
    { 
        hRes=pSL->SetIDList(pidl);
        if(SUCCEEDED(hRes))
        { 
            hRes = pSL->SetHotkey(wHotKey); 
            if( SUCCEEDED(hRes) ) 
            { 
                hRes = pSL->SetShowCmd(iCmdShow); 
                if( SUCCEEDED(hRes) ) 
                { 
                    hRes = pSL->QueryInterface(IID_IPersistFile,(LPVOID *)&pPF); 
                    if( SUCCEEDED(hRes) ) 
                    { 
                        hRes = pPF->Save(pwzShortCutFileName,TRUE); 
                        pPF->Release(); 
                    }
                }
            }
        }
        pSL->Release(); 
    }
    return SUCCEEDED(hRes); 
}

/******************************************************************************/
/* Functions copied from http://msdn.microsoft.com */

LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl) 
{ 
   // Check for valid pidl.
   if(pidl == NULL)
      return NULL;

   // Get the size of the specified item identifier. 
   int cb = pidl->mkid.cb; 

   // If the size is zero, it is the end of the list. 

   if (cb == 0) 
      return NULL; 

   // Add cb to pidl (casting to increment by bytes). 
   pidl = (LPITEMIDLIST) (((LPBYTE) pidl) + cb); 

   // Return NULL if it is null-terminating, or a pidl otherwise. 
   return (pidl->mkid.cb == 0) ? NULL : (LPITEMIDLIST) pidl; 
} 

/* Get size of PIDL */
UINT GetSize(LPCITEMIDLIST pidl)
{
    UINT cbTotal = 0;
    if (pidl)
    {
        cbTotal += sizeof(pidl->mkid.cb);    // Terminating null character
        while (pidl)
        {
            cbTotal += pidl->mkid.cb;
            pidl = GetNextItemID(pidl);
        }
    }
    return cbTotal;
}

/* Appending PIDLs */
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd)
{
    if(pidlBase == NULL)
        return NULL;
    if(pidlAdd == NULL)
        return (LPITEMIDLIST)pidlBase;
    
    LPITEMIDLIST pidlNew;

    UINT cb1 = GetSize(pidlBase) - sizeof(pidlBase->mkid.cb);
    UINT cb2 = GetSize(pidlAdd);

    pidlNew = (LPITEMIDLIST)pMalloc->Alloc(cb1 + cb2);
    if (pidlNew)
    {
        CopyMemory(pidlNew, pidlBase, cb1);
        CopyMemory(((LPSTR)pidlNew) + cb1, pidlAdd, cb2);
    }
    return pidlNew;
}

Но при компиляции появляются ошибки:

error C2664: CreateLinkThenChangeIcon: невозможно преобразовать параметр 1 из 'const char [9]' в 'LPTSTR'	

Ошибка	7	error C2061: синтаксическая ошибка: идентификатор "_TCHAR"	

Ошибка	6	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	5	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [13]' в 'LPCWSTR'	

Ошибка	4	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	3	error C2664: MultiByteToWideChar: невозможно преобразовать параметр 3 из 'TCHAR [256]' в 'LPCSTR'	

Ошибка	2	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [2]' в 'LPCWSTR'	

Код работал, может я чего то с библиотеками намутил? Ткните носом пожалуйста…

aprkaer

0 / 0 / 0

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

Сообщений: 9

1

19.05.2013, 12:44. Показов 17514. Ответов 19

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


Студворк — интернет-сервис помощи студентам

Программа по обходу в глубину графа. вылетает error C2061: синтаксическая ошибка: идентификатор «_TCHAR».
что с этим делать?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 2w3.cpp: главный файл проекта.
 
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>
#include <windows.h>
using namespace System;
using namespace std;
 
vector<vector<int>> Mat;
vector<int> Vec;
vector<char> used;
void dfs (int v) {
    used[v] = true;
    for (int i=0; Mat.size(); ++i)
        if (!used[i])
            dfs (i);
}
 
/////////////////////////Функция русификации////////////////////////////
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}
int main(int argc, _TCHAR* argv[]){
 
    cout<<Rus("Введите количество вершин:");
    int nCount,i=0;
    cin>>nCount;
    while(i!=nCount){
        cout<<Rus("Введите строку списка, если захотите закончить ввод нажмите -1:")<<endl;
        int op;
        for(int j=0;;++j){
            cin>>op;
            if(op!=-1){Vec.push_back(op);}
            else {break;}
        }
        Mat.push_back(Vec);
        Vec.clear();
        ++i;
    }
    cout<<Rus("Введите вершину, с которой вы хотите построить пвг:");
    int v;
    cin>>v;
    dfs(v);
    
    return 0;
}

0

5495 / 4890 / 831

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

Сообщений: 13,587

19.05.2013, 12:56

2

Цитата
Сообщение от aprkaer
Посмотреть сообщение

что с этим делать?

Заменить на char.

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 14:19

 [ТС]

3

ха-ха. если б всё так просто.

0

alsav22

5495 / 4890 / 831

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

Сообщений: 13,587

19.05.2013, 14:29

4

Какой вопрос — такой и ответ. Вставляю ваш код в студию, заменяю, и компиляция без ошибок.

Добавлено через 6 минут
Ещё вариант:

C++
1
#include <tchar.h>

0

Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:34

5

Цитата
Сообщение от aprkaer
Посмотреть сообщение

int main(int argc, _TCHAR* argv[])

может просто написать?

C++
1
int main()

0

alsav22

5495 / 4890 / 831

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

Сообщений: 13,587

19.05.2013, 14:37

6

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

может просто написать?

C++
1
int main()

Я так понял, что ТС нужно использовать _TCHAR.

0

Issues

433 / 368 / 149

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

Сообщений: 961

19.05.2013, 14:42

7

Цитата
Сообщение от alsav22
Посмотреть сообщение

Я так понял, что ТС нужно использовать _TCHAR.

но ведь он как и

C++
1
using namespace System;

в программе нигде не используется.

0

Croessmah

19.05.2013, 14:43

#8

Не по теме:

alsav22, не думаю что ему нужен TCHAR:

C++
1
2
3
4
5
char *Rus(char *ps){
    char *buf=new char[strlen(ps)];
    CharToOemA(ps,buf);
    return buf;
}

0

alsav22

19.05.2013, 14:50

Не по теме:

Тогда я не понимаю его третий пост.

0

Issues

19.05.2013, 14:54

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

Тогда я не понимаю его третий пост.

скорее всего он вставляет этот код в простой «Win32 Console Application»

0

alsav22

19.05.2013, 14:59

Не по теме:

Цитата
Сообщение от SeregaC++
Посмотреть сообщение

Не по теме:

скорее всего он вставляет этот код в простой «Win32 Console Application»

И что, в нём нельзя заменить _TCHAR на char?

0

Issues

19.05.2013, 15:02

Не по теме:

Цитата
Сообщение от alsav22
Посмотреть сообщение

И что, в нём нельзя заменить _TCHAR на char?

можно.

0

Croessmah

19.05.2013, 15:04

Не по теме:

Да что мы гадаем…нам за это не платят — зайдет пояснит

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 21:32

 [ТС]

14

TCAR на char не канает, оибки и добавление #include char тоже.

0

5495 / 4890 / 831

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

Сообщений: 13,587

19.05.2013, 23:34

15

Не по теме:

Цитата
Сообщение от Croessmah
Посмотреть сообщение

Да что мы гадаем…нам за это не платят — зайдет пояснит

Пояснил, называется…

Цитата
Сообщение от aprkaer
Посмотреть сообщение

и добавление #include char тоже

А #include <tchar.h> ? Что за среда? Проект?

0

0 / 0 / 0

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

Сообщений: 9

19.05.2013, 23:59

 [ТС]

16

CLR console application/ visual studio 2010

0

Неэпический

17808 / 10579 / 2043

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

Сообщений: 26,612

Записей в блоге: 1

20.05.2013, 00:12

17

C++ и C++/CLI разные языки.

0

5495 / 4890 / 831

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

Сообщений: 13,587

20.05.2013, 00:13

18

Цитата
Сообщение от aprkaer
Посмотреть сообщение

TCAR на char не канает, ошибки

Ошибки какие?

0

0 / 0 / 0

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

Сообщений: 9

20.05.2013, 00:27

 [ТС]

19

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Добавлено через 1 минуту
Пришли пожалуйста EXE-шник, если компилится. zelenyy81@mail.ru

0

5495 / 4890 / 831

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

Сообщений: 13,587

20.05.2013, 01:07

20

Цитата
Сообщение от aprkaer
Посмотреть сообщение

error C2061: синтаксическая ошибка: идентификатор «_TCHAR»

Если заменить _TCAR на char? Откуда там такая ошибка может взяться, если _TCHAR уже нет?

Добавлено через 12 минут
Ошибки там другие появляются, компоновщик выдаёт:

1>—— Построение начато: проект: CLR3Cons, Конфигурация: Debug Win32 ——
1> CLR3Cons.cpp
1>CLR3Cons.obj : error LNK2028: ссылка на неразрешенную лексему (0A000408) «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>CLR3Cons.obj : error LNK2019: ссылка на неразрешенный внешний символ «extern «C» int __stdcall CharToOemA(char const *,char *)» (?CharToOemA@@$$J18YGHPBDPAD@Z) в функции «extern «C» char * __cdecl Rus(char const *)» (?Rus@@$$J0YAPADPBD@Z)
1>D:MY C++ProjectsCLR3ConsDebugCLR3Cons.exe : fatal error LNK1120: 2 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Не находит реализацию для CharToOemA()?

Добавлено через 7 минут

Цитата
Сообщение от aprkaer
Посмотреть сообщение

Пришли пожалуйста EXE-шник, если компилится.

Тут всё дело в пректе. Компилится без проблем, если проект не CLR.

0

Прошу не убивать и не крыть матом, снова с проблемами…

Имеется следующий код, который выводит программно ярлык из папки «сетевые подключения». 

#include <stdio.h>
#include <shlobj.h>
#include <shlwapi.h>

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow);
int short_cut_startup(char *connection_name, LPWSTR link_name);
LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl);
UINT GetSize(LPCITEMIDLIST pidl);
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd);

LPMALLOC pMalloc;

int main(void)
{
    if(short_cut_startup("demo", L"demo.lnk"))
        printf("Success!n");
    else printf("Can't create shortcut!n");
    return 0;
}

/* Main function which creating shortcut on desktop */
int short_cut_startup(char *connection_name, LPWSTR link_name)
{
    LPITEMIDLIST pidConnections = NULL;
    LPITEMIDLIST pidlItems = NULL;
    LPITEMIDLIST pidlDesk = NULL;
    IShellFolder *psfFirstFolder = NULL;
    IShellFolder *psfDeskTop = NULL;
    IShellFolder *pConnections = NULL;
    LPENUMIDLIST ppenum = NULL;
    ULONG celtFetched;
    HRESULT hr;
    STRRET str_curr_connection_name;
    TCHAR curr_connection_name[MAX_PATH] = "";    /* Connection point name */
    TCHAR desktop_path[MAX_PATH]="";            /* Path to desktop */
    TCHAR full_link_name[MAX_PATH]="";            /* Full shortcut name */
    LPITEMIDLIST full_pid;                        /* Full shortcut pid */

   
    CoInitialize( NULL );
    /* Allocating memory for Namespace objects */
    hr = SHGetMalloc(&pMalloc);
    hr = SHGetFolderLocation(NULL, CSIDL_CONNECTIONS, NULL, NULL, &pidConnections);

    /* Get full path to desktop */
    SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);

    hr = SHGetDesktopFolder(&psfDeskTop);
    hr = psfDeskTop->BindToObject(pidConnections, NULL, IID_IShellFolder, (LPVOID *) &pConnections);
    hr = pConnections->EnumObjects(NULL,SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &ppenum);

    /* Loop for searching our connection */
    while(hr = ppenum->Next(1,&pidlItems, &celtFetched) == S_OK && (celtFetched) == 1)
    {
        pConnections->GetDisplayNameOf(pidlItems, SHGDN_INFOLDER, &str_curr_connection_name);
        StrRetToBuf(&str_curr_connection_name, pidlItems, curr_connection_name, MAX_PATH);
        if(!strcmp(curr_connection_name,connection_name))
            goto found;
    }
    printf("Connection not found in "Network connections" folder.n");
    return 0;
found:
    /* Append PIDLs */
    full_pid=Append(pidConnections,pidlItems);
    SetCurrentDirectory(desktop_path);
    if(!CreateShortCut(link_name, full_pid, "C:windows", 0, SW_SHOWNORMAL))
        return 0;

    ppenum->Release();
    pMalloc->Free(pidlItems);
    pMalloc->Free(pidConnections);
    pMalloc->Release();
    pConnections->Release();
    CoUninitialize();
    return 1;
}

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow)
{ 
    IShellLink * pSL; 
    IPersistFile * pPF; 
    HRESULT hRes; 
    hRes = CoCreateInstance(CLSID_ShellLink, 0,CLSCTX_INPROC_SERVER, 
                            IID_IShellLink, (LPVOID *)&pSL); 
    if( SUCCEEDED(hRes) ) 
    { 
        hRes=pSL->SetIDList(pidl);
        if(SUCCEEDED(hRes))
        { 
            hRes = pSL->SetHotkey(wHotKey); 
            if( SUCCEEDED(hRes) ) 
            { 
                hRes = pSL->SetShowCmd(iCmdShow); 
                if( SUCCEEDED(hRes) ) 
                { 
                    hRes = pSL->QueryInterface(IID_IPersistFile,(LPVOID *)&pPF); 
                    if( SUCCEEDED(hRes) ) 
                    { 
                        hRes = pPF->Save(pwzShortCutFileName,TRUE); 
                        pPF->Release(); 
                    }
                }
            }
        }
        pSL->Release(); 
    }
    return SUCCEEDED(hRes); 
}

/******************************************************************************/
/* Functions copied from http://msdn.microsoft.com */

LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl) 
{ 
   // Check for valid pidl.
   if(pidl == NULL)
      return NULL;

   // Get the size of the specified item identifier. 
   int cb = pidl->mkid.cb; 

   // If the size is zero, it is the end of the list. 

   if (cb == 0) 
      return NULL; 

   // Add cb to pidl (casting to increment by bytes). 
   pidl = (LPITEMIDLIST) (((LPBYTE) pidl) + cb); 

   // Return NULL if it is null-terminating, or a pidl otherwise. 
   return (pidl->mkid.cb == 0) ? NULL : (LPITEMIDLIST) pidl; 
} 

/* Get size of PIDL */
UINT GetSize(LPCITEMIDLIST pidl)
{
    UINT cbTotal = 0;
    if (pidl)
    {
        cbTotal += sizeof(pidl->mkid.cb);    // Terminating null character
        while (pidl)
        {
            cbTotal += pidl->mkid.cb;
            pidl = GetNextItemID(pidl);
        }
    }
    return cbTotal;
}

/* Appending PIDLs */
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd)
{
    if(pidlBase == NULL)
        return NULL;
    if(pidlAdd == NULL)
        return (LPITEMIDLIST)pidlBase;
    
    LPITEMIDLIST pidlNew;

    UINT cb1 = GetSize(pidlBase) - sizeof(pidlBase->mkid.cb);
    UINT cb2 = GetSize(pidlAdd);

    pidlNew = (LPITEMIDLIST)pMalloc->Alloc(cb1 + cb2);
    if (pidlNew)
    {
        CopyMemory(pidlNew, pidlBase, cb1);
        CopyMemory(((LPSTR)pidlNew) + cb1, pidlAdd, cb2);
    }
    return pidlNew;
}

Но при компиляции появляются ошибки:

error C2664: CreateLinkThenChangeIcon: невозможно преобразовать параметр 1 из 'const char [9]' в 'LPTSTR'	

Ошибка	7	error C2061: синтаксическая ошибка: идентификатор "_TCHAR"	

Ошибка	6	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	5	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [13]' в 'LPCWSTR'	

Ошибка	4	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	3	error C2664: MultiByteToWideChar: невозможно преобразовать параметр 3 из 'TCHAR [256]' в 'LPCSTR'	

Ошибка	2	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [2]' в 'LPCWSTR'	

Код работал, может я чего то с библиотеками намутил? Ткните носом пожалуйста…

Не могу понять, почему я получаю эту ошибку? im kinda новичок в С++ и визуальной студии Microsoft, что-то потерянное на этом. Спасибо за помощь по продвижению.

#include <iostream>                          
#include <fstream>                           
#include <string>                       
#include <windows.h>                        

using namespace std;
#define STILL_PLAYING   1
#define QUIT            0
#define GAME_FILE "Mundo.txt";

////// the main class of the game, its a room, ull be moving around to other rooms. /////////////
struct posicao{
    string posAtual;
    string Descricao;
    string posNorte;
    string posSul;
    string posLeste;
    string posOeste;
};

/////////// displays the room that you are at the moment /////
void mostraposicao(posicao &posicao)
{
    cout << posicao.Descricao << endl << endl;
}

////////// gets all info of the present room ////
void getPosicaoInfo(posicao &posicao, ifstream fin) {
    string strLine = "";
    string strTemp = "";

    string strPosicao = "<" + posicao.posAtual + ">";
    fin.seekg(NULL, ios::beg);
    fin.clear();

    // reads the txt file line by line till it reaches '*' because
    // the room description is in this format --->> "text '*'"
    // to identify the end of the description.
    while (getline(fin, strLine, 'n')) {
        if (strLine == strPosicao) {
            getline(fin, posicao.Descricao, '*');
            fin >> strTemp >> posicao.posNorte;
            fin >> strTemp >> posicao.posSul;
            fin >> strTemp >> posicao.posLeste;
            fin >> strTemp >> posicao.posOeste;
            return;
        }
    }
}

//// moves to another room////////
void Andar(ifstream fin, posicao &posicao, string strPosicao) {
    if (string == "None") {
        cout << "Você não pode ir por ai!!!" << endl;
        return;
    }
    posicao.posAtual = strPosicao;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);
}

//////////get the input of the player ///////////
int getComando(ifstream fin, posicao &posicao) {
    string strComando = "";
    cout <<endl << ":";
    cin >> strComando;
    if (strComando == "Olhar") {
        mostraposicao(posicao);
    }
    else if(strComando == "Norte") {
        Andar(fin, posicao, posicao.posNorte);
    }
    else if (strComando == "Sul") {
        Andar(fin, posicao, posicao.posSul);
    }
    else if (strComando == "Leste") {
        Andar(fin, posicao, posicao.posLeste);
    }
    else if (strComando == "Oeste") {
        Andar(fin,posicao,posicao.posOeste)
    }
    else if (strComando == "Sair") {
        cout << "Você já desistiu?" << endl;
        return QUIT;
    }
    else if (strComando == "Ajuda" || strComando == "?") {
        cout << endl << "Os comandos do jogo sao : Olhar, Norte, Sul, Leste,Oeste,Sair,Ajuda" << endl;
    }
    else {
        cout << "Ahñ???" << endl;
    }
    return STILL_PLAYNG;
}

///// where the game begins //////////
int _tmain(int argc, _TCHAR* argv[])
{
    ifstream fin;    /// creates the stream file ///
    posicao posicao;   //// the room that will be used in the game ///
    fin.open(GAME_FILE);   ///// gets the text file////
    if (fin.fail())   /////// if the text doesnt exist, the game ends ////
    {
        // Display a error message and return -1 (Quit the program)
        cout << "Jogo não encontrado" << endl;
        return -1;
    }
    // reads twice, so it skips the <start> and reads the <middle>
    // (first room ull be in the game
    fin >> posicao.posAtual >> posicao.posAtual;
    getPosicaoInfo(fin, posicao);
    mostraposicao(posicao);

    /////// if the input its quit, ends the game//////
    while (1) {
        if (getComando(fin, posicao) == QUIT)
            break;
    }
    /////// closes the txt file, ends the game//////////
    fin.close();
    Sleep(3000); /// delays  the close///
    return 0;
}

текст находится в таком формате:

<Start> Middle

<Middle>
You step into a house where you are nearly
blinded by the light shinning through the window.
You have been searching for your friend who was captured.
The trail has led you to this mansion.
There is a door in every direction.*
<north> Top
<east>  Right
<south> Bottom
<west>  Left

<Left>
There is a fountain in the middle of this room.
The cool, crisp air swirls about and encircles you.
There is only one door to the east where you came.*
<north> None
<east>  Middle
<south> None
<west>  None

<Bottom>
You step back outside of the mansion and grab some fresh air.
It is quite refreshing, comapred to the damp smell from within.
You here rustling from the second story of the house.  It could be your friend.
Your only option is to go back inside and get them out of here!*
<north> Middle
<east>  None
<south> None
<west>  None

<Right>
As you pass through the door you feel a chill run
down your spine.  It appears that there something or 
someone or something sitting in the corner, covered by darkness.
There is no where to go but back to the west.*
<north> None
<east>  None
<south> None
<west>  Middle

<Top>
As you get closer to the second story of the mansion, the sounds of someone
struggling can be heard more distinctly.  There is no turning back now.
One door is to the south and one is to the north up a stairwell.*
<north> End
<east>  None
<south> Middle
<west>  None

<End>
You find your friend tied to a chair.  Their hands, feet and mouth are bound,
but it as if their eyes are screaming at you.  Short bursts of muffled yells
are heard from under the cloth that holds their mouth, as if to say, "Run!".  
What could they be trying to say?  As you walk closer to them they seem to get 
louder and more depserate. That when you see it.  It had been lurching in the
corner, feathered by darkness.   To be continued...*
<north> None
<east>  None
<south> None
<west>  None

123Alexander

  • #1

В строке:
int _tmain(int argc, _TCHAR* argv[]);
пишет сообщение
error C2061: syntax error : identifier ‘_TCHAR’
Что это может означать? Не получается исправить.

SunSanych

  • #2

а если попробовать без первого подчёркивания в TCHAR?
Тоесть так:

Код:

int _tmain(int argc, TCHAR* argv[]);

или забыли включить tchar.h перед определением _tmain.
Тоесть так:

Код:

#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[]);

123Alexander

  • #3

Я вот так сделал:
int _tmain(int argc, char* argv[]); — ошибка исчезла

Но осталась ещё одна, последняя.
В строке
{
пишет ошибку:
error C2447: missing function header (old-style formal list?)

Всё выглядит так:
//Ââîäèòü äâà ÷èñëà è èñêàòü èõ ñóììó äî òåõ ïîð, ïîêà ïåðâîå ÷èñëî
//íå áóäåò ââåäåíî ðàâíûì 1. Ââîäèòü äâà ÷èñëà è èñêàòü èõ ðàçíèöó
//äî òåõ ïîð, ïîêà îíà íå áóäåò ðàâíà 0.

int _tmain(int argc, char* argv[]);
{
float t;
float x1;
float x2;
float s;
int i = 0;
while ( i <=1 )
{
printf(«Read x1=»);
scanf(«%f»,&x1);
printf(«Read x2=»);
scanf(«%f»,&x2);
s=x1-x2;
if (x1=1) i=2;
else if (s=0) i=3;
}
if (i=2) printf(«Uslovie 1n»);
else printf(«Uslovie 2n»);
scanf(«%f»,&t);
return 0;
}

European

  • #4

Для: 123Alexander
Ты же входные аргументы не обрабатываешь, да и tchar не используешь, так сделай:

Код:

int main()
{
// .... place code here
return 0;
}

Я пытаюсь изучать C ++, однако, параметр метода, который у меня есть в моем собственном классе, ведет себя неправильно. Когда он использует dataType типа int, он отлично работает без ошибок, но когда я пытаюсь изменить его на «string» dataType, программа вылетает с этой ошибкой.

Ошибка 1 ошибка C2061: синтаксическая ошибка: идентификатор ‘строка’ в файле temp.h ln
8 цв 1

Я использую следующие классы:

РАБОЧИЙ КОД
TesterClass.cpp // Точка входа

#include "stdafx.h"#include "Temp.h"
int _tmain(int argc, _TCHAR* argv[])
{
Temp tmp;
tmp.doSomething(7);

return 0;
}

Temp.h

#pragma once

class Temp
{
public:
Temp();

void doSomething(int blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>

using std::string;

Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}

void Temp::doSomething(int blah)
{
std::cout << blah;
}

Сломанный код
Temp.h

#pragma once

class Temp
{
public:
Temp();

void doSomething(string blah);
};

Temp.cpp

#include "stdafx.h"#include "Temp.h"
#include <iostream>
#include <string>

using std::string;

Temp::Temp()
{
std::cout << "Entry" << std::endl;
string hi;
std::cin >> hi;
std::cout << hi << std::endl;
}

void Temp::doSomething(string blah)
{
std::cout << blah;
}

Когда я настраиваю параметр «blah» на строку, как в файле .h, так и в файле .cpp, возникает проблема.

Я огляделся, но ни один из ответов, похоже, не решил мою проблему. Я очень хотел бы помочь в этом, я вне идей. Я попытался переустановить C ++, возиться с:

using namepace std;
using std::string;
std::string instead of string
etc.

Если вы знаете, как решить мою проблему, я хотел бы услышать от вас. Я более чем рад предоставить больше информации.

-3

Решение

C ++ выполняет однопроходную компиляцию, поэтому std :: string необходимо объявить перед тем, как использовать его вообще — в том числе в заголовочном файле.

// Temp.h
#pragma once

#include <string>

class Temp
{
public:
Temp();

void doSomething(std::string blah);
};

Я бы посоветовал вам быть более точным в ваших заголовочных файлах при указании таких классов, потому что вы можете легко встретить другую библиотеку, которая определяет свою собственную string и тогда вы столкнетесь с конфликтами имен. Спасти using импортировать операторы для ваших файлов cpp.

0

Другие решения

У πάντα ῥεῖ был письменный ответ, спасибо!

Они сказали использовать std :: string при необходимости, а также #include <string> в заголовочном файле.

0

123Alexander

  • #1

В строке:
int _tmain(int argc, _TCHAR* argv[]);
пишет сообщение
error C2061: syntax error : identifier ‘_TCHAR’
Что это может означать? Не получается исправить.

SunSanych

  • #2

а если попробовать без первого подчёркивания в TCHAR?
Тоесть так:

Код:

int _tmain(int argc, TCHAR* argv[]);

или забыли включить tchar.h перед определением _tmain.
Тоесть так:

Код:

#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[]);

123Alexander

  • #3

Я вот так сделал:
int _tmain(int argc, char* argv[]); — ошибка исчезла

Но осталась ещё одна, последняя.
В строке
{
пишет ошибку:
error C2447: missing function header (old-style formal list?)

Всё выглядит так:
//Ââîäèòü äâà ÷èñëà è èñêàòü èõ ñóììó äî òåõ ïîð, ïîêà ïåðâîå ÷èñëî
//íå áóäåò ââåäåíî ðàâíûì 1. Ââîäèòü äâà ÷èñëà è èñêàòü èõ ðàçíèöó
//äî òåõ ïîð, ïîêà îíà íå áóäåò ðàâíà 0.

int _tmain(int argc, char* argv[]);
{
float t;
float x1;
float x2;
float s;
int i = 0;
while ( i <=1 )
{
printf(«Read x1=»);
scanf(«%f»,&x1);
printf(«Read x2=»);
scanf(«%f»,&x2);
s=x1-x2;
if (x1=1) i=2;
else if (s=0) i=3;
}
if (i=2) printf(«Uslovie 1n»);
else printf(«Uslovie 2n»);
scanf(«%f»,&t);
return 0;
}

European

  • #4

Для: 123Alexander
Ты же входные аргументы не обрабатываешь, да и tchar не используешь, так сделай:

Код:

int main()
{
// .... place code here
return 0;
}

Прошу не убивать и не крыть матом, снова с проблемами… :)

Имеется следующий код, который выводит программно ярлык из папки «сетевые подключения». 

#include <stdio.h>
#include <shlobj.h>
#include <shlwapi.h>

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow);
int short_cut_startup(char *connection_name, LPWSTR link_name);
LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl);
UINT GetSize(LPCITEMIDLIST pidl);
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd);

LPMALLOC pMalloc;

int main(void)
{
    if(short_cut_startup("demo", L"demo.lnk"))
        printf("Success!n");
    else printf("Can't create shortcut!n");
    return 0;
}

/* Main function which creating shortcut on desktop */
int short_cut_startup(char *connection_name, LPWSTR link_name)
{
    LPITEMIDLIST pidConnections = NULL;
    LPITEMIDLIST pidlItems = NULL;
    LPITEMIDLIST pidlDesk = NULL;
    IShellFolder *psfFirstFolder = NULL;
    IShellFolder *psfDeskTop = NULL;
    IShellFolder *pConnections = NULL;
    LPENUMIDLIST ppenum = NULL;
    ULONG celtFetched;
    HRESULT hr;
    STRRET str_curr_connection_name;
    TCHAR curr_connection_name[MAX_PATH] = "";    /* Connection point name */
    TCHAR desktop_path[MAX_PATH]="";            /* Path to desktop */
    TCHAR full_link_name[MAX_PATH]="";            /* Full shortcut name */
    LPITEMIDLIST full_pid;                        /* Full shortcut pid */

   
    CoInitialize( NULL );
    /* Allocating memory for Namespace objects */
    hr = SHGetMalloc(&pMalloc);
    hr = SHGetFolderLocation(NULL, CSIDL_CONNECTIONS, NULL, NULL, &pidConnections);

    /* Get full path to desktop */
    SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktop_path);

    hr = SHGetDesktopFolder(&psfDeskTop);
    hr = psfDeskTop->BindToObject(pidConnections, NULL, IID_IShellFolder, (LPVOID *) &pConnections);
    hr = pConnections->EnumObjects(NULL,SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &ppenum);

    /* Loop for searching our connection */
    while(hr = ppenum->Next(1,&pidlItems, &celtFetched) == S_OK && (celtFetched) == 1)
    {
        pConnections->GetDisplayNameOf(pidlItems, SHGDN_INFOLDER, &str_curr_connection_name);
        StrRetToBuf(&str_curr_connection_name, pidlItems, curr_connection_name, MAX_PATH);
        if(!strcmp(curr_connection_name,connection_name))
            goto found;
    }
    printf("Connection not found in "Network connections" folder.n");
    return 0;
found:
    /* Append PIDLs */
    full_pid=Append(pidConnections,pidlItems);
    SetCurrentDirectory(desktop_path);
    if(!CreateShortCut(link_name, full_pid, "C:\windows", 0, SW_SHOWNORMAL))
        return 0;

    ppenum->Release();
    pMalloc->Free(pidlItems);
    pMalloc->Free(pidConnections);
    pMalloc->Release();
    pConnections->Release();
    CoUninitialize();
    return 1;
}

bool __fastcall CreateShortCut(LPWSTR pwzShortCutFileName,  LPCITEMIDLIST pidl,
                               LPTSTR pszWorkingDirectory, WORD wHotKey, int iCmdShow)
{ 
    IShellLink * pSL; 
    IPersistFile * pPF; 
    HRESULT hRes; 
    hRes = CoCreateInstance(CLSID_ShellLink, 0,CLSCTX_INPROC_SERVER, 
                            IID_IShellLink, (LPVOID *)&pSL); 
    if( SUCCEEDED(hRes) ) 
    { 
        hRes=pSL->SetIDList(pidl);
        if(SUCCEEDED(hRes))
        { 
            hRes = pSL->SetHotkey(wHotKey); 
            if( SUCCEEDED(hRes) ) 
            { 
                hRes = pSL->SetShowCmd(iCmdShow); 
                if( SUCCEEDED(hRes) ) 
                { 
                    hRes = pSL->QueryInterface(IID_IPersistFile,(LPVOID *)&pPF); 
                    if( SUCCEEDED(hRes) ) 
                    { 
                        hRes = pPF->Save(pwzShortCutFileName,TRUE); 
                        pPF->Release(); 
                    }
                }
            }
        }
        pSL->Release(); 
    }
    return SUCCEEDED(hRes); 
}

/******************************************************************************/
/* Functions copied from http://msdn.microsoft.com */

LPITEMIDLIST GetNextItemID(LPCITEMIDLIST pidl) 
{ 
   // Check for valid pidl.
   if(pidl == NULL)
      return NULL;

   // Get the size of the specified item identifier. 
   int cb = pidl->mkid.cb; 

   // If the size is zero, it is the end of the list. 

   if (cb == 0) 
      return NULL; 

   // Add cb to pidl (casting to increment by bytes). 
   pidl = (LPITEMIDLIST) (((LPBYTE) pidl) + cb); 

   // Return NULL if it is null-terminating, or a pidl otherwise. 
   return (pidl->mkid.cb == 0) ? NULL : (LPITEMIDLIST) pidl; 
} 

/* Get size of PIDL */
UINT GetSize(LPCITEMIDLIST pidl)
{
    UINT cbTotal = 0;
    if (pidl)
    {
        cbTotal += sizeof(pidl->mkid.cb);    // Terminating null character
        while (pidl)
        {
            cbTotal += pidl->mkid.cb;
            pidl = GetNextItemID(pidl);
        }
    }
    return cbTotal;
}

/* Appending PIDLs */
LPITEMIDLIST Append(LPCITEMIDLIST pidlBase, LPCITEMIDLIST pidlAdd)
{
    if(pidlBase == NULL)
        return NULL;
    if(pidlAdd == NULL)
        return (LPITEMIDLIST)pidlBase;
    
    LPITEMIDLIST pidlNew;

    UINT cb1 = GetSize(pidlBase) - sizeof(pidlBase->mkid.cb);
    UINT cb2 = GetSize(pidlAdd);

    pidlNew = (LPITEMIDLIST)pMalloc->Alloc(cb1 + cb2);
    if (pidlNew)
    {
        CopyMemory(pidlNew, pidlBase, cb1);
        CopyMemory(((LPSTR)pidlNew) + cb1, pidlAdd, cb2);
    }
    return pidlNew;
}

Но при компиляции появляются ошибки:

error C2664: CreateLinkThenChangeIcon: невозможно преобразовать параметр 1 из 'const char [9]' в 'LPTSTR'	

Ошибка	7	error C2061: синтаксическая ошибка: идентификатор "_TCHAR"	

Ошибка	6	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	5	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [13]' в 'LPCWSTR'	

Ошибка	4	error C2664: IPersistFile::Save: невозможно преобразовать параметр 1 из 'WORD [256]' в 'LPCOLESTR'	

Ошибка	3	error C2664: MultiByteToWideChar: невозможно преобразовать параметр 3 из 'TCHAR [256]' в 'LPCSTR'	

Ошибка	2	error C2664: lstrcatW: невозможно преобразовать параметр 2 из 'const char [2]' в 'LPCWSTR'	

Код работал, может я чего то с библиотеками намутил? Ткните носом пожалуйста…

I am trying to port a component that runs fine on Microsoft Visual studio
The component has the following code in it

if ( SuperNode.someMethod == _T( "Hello" ) )    

When attempting to build the code in gcc cygwin I get the following error

error: '_T' was not declared in this scope|

Now in visual studio _T points to tchar.h
Which has something like this

#define _T(x)       __T(x)
#define _TEXT(x)    __T(x)

What could I do to fix this problem for gcc cygwin ? Ill be running it on windows

asked Jan 28, 2015 at 19:21

MistyD's user avatar

2

As discussed for instance at tchar.h not found on cygwin , Cygwin (being a compatibility layer which attempts to emulate the POSIX programming interface on top of Windows) has more in common with a Unix implementation than it does Windows. In particular, it does not provide tchar.h.

What you should do about this depends on your larger goals: why are you trying to compile this program using something other than Visual Studio? Here are some possibilities:

  • You want a more standard-conforming C++ implementation than VS2010 provides, but you still want to build a native Windows application. The path of least resistance is probably to switch to a newer version of Visual Studio instead; the «Express» editions of these are free-as-in-beer. You could also try MinGW, which is a GCC backend that produces native Windows applications, and Clang for Windows.

  • You need to interoperate at the ABI level with (e.g. load DLLs into) a C++ program that was compiled using MinGW. In that case you should also be using MinGW. (Clang-for-Windows is supposed to be ABI-compatible with Visual Studio, so it won’t work in this case. Note that if the ABI involved is specified entirely in plain C, then there should be no problem loading a Visual Studio-compiled DLL into a MinGW-compiled program or vice versa.)

  • This is stage one of a port to Unix (note: for purpose of this discussion, MacOS X counts as Unix), or you need to interoperate at the ABI level with a Cygwin program … which means you have to port to Unix. In that case, stage zero needs to be stop using tchar.h.

    What I mean by that is, go back to your Visual Studio builds, and then find every place in your code that uses anything defined in tchar.h (_TCHAR, _T, _TEXT, _tcs*, probably others) and change them to use either plain char, or wchar_t, as appropriate, and the associated string-literal syntax and functions. You should also wean yourself off the generic (neither A nor W suffix) variant of the core Windows API at the same time. I believe there is a macro you can define that causes windows.h not to provide the generic API at all, but I don’t remember what it is and can’t find it on MSDN right now.

    Keep in mind while doing this that Unix prefers you to use UTF-8-coded text in char/std::string, rather than UTF-16 text in wchar_t/std::wstring etc. It has been my experience that a cross-platform application is generally happiest conforming to the Unix convention except in the functions that talk directly to the Windows API, which use exclusively the W variants of that API, converting back and forth right then and there. (And you need to create yourself a compatibility layer and isolate all of that code there and arrange to have as little of it as possible.)

answered Jan 28, 2015 at 19:30

zwol's user avatar

zwolzwol

136k38 gold badges252 silver badges362 bronze badges

In the Visual Studio headers, _T is defined to be L if compiling with wide character support, or nothing otherwise.

So if wide character support is enabled, _T("blah blah blah") will get preprocessed to L"blah blah blah".

If wide character support is disabled, _T("blah blah blah") will get preprocessed to "blah blah blah".

answered Jan 28, 2015 at 19:28

Jeff Loughlin's user avatar

Jeff LoughlinJeff Loughlin

4,1442 gold badges30 silver badges47 bronze badges

3

Понравилась статья? Поделить с друзьями:
  • Синтаксическая ошибка непредвиденный токен требуется объявление
  • Синтаксическая ошибка идентификатор form1
  • Синтаксическая ошибка идентификатор file
  • Синтаксическая ошибка неожиданный символ после символа продолжения строки
  • Синтаксическая ошибка и настройкагруппировкиобщейнастройки этодействующийпараметр