0 / 0 / 0 Регистрация: 22.02.2015 Сообщений: 38 |
|
1 |
|
02.06.2015, 17:44. Показов 15928. Ответов 2
Добрый день!
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
02.06.2015, 17:44 |
2 |
Заблокирован |
|
02.06.2015, 18:04 |
2 |
Знаю, что вопрос глупый Верно подмечено
IntelliSense: идентификатор «_TCHAR» не определен То, что IntelliSense не смог распознать, это не ошибка. Ошибки, мешающие сборке — это ошибки компилятора.
_TCHAR» не определен значит не подключен файл #include <tchar.h> не удается открыть источник файл «stdafx.h» то и се ля ви. В общем ты не весь проект скопировал на другой комп, копируй весь, включая файл stdafx.h
2 |
lss 940 / 868 / 355 Регистрация: 10.10.2012 Сообщений: 2,706 |
||||
02.06.2015, 18:23 |
3 |
|||
Решение
может, поможете? Вот так измени (будет стандарт):
Убери #include «stdafx.h» и, в свойствах проекта, С/С++, Предварительно откомпилированные заголовки, выбери: Не использовать предварительно скомпилированные заголовки.
1 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
02.06.2015, 18:23 |
3 |
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
При создании в 2008й вс консольного приложения функция main() имеет следующий вид:
int _tmain(int argc, _TCHAR* argv[])
и при попытке получить параметры ком.строки (если обрабатывать как С-строки) получается абракадабра вместо введенных параметров.
// На мсдн вычитал, что тчар обусловлен «юникодностью» параметров.
И вот, собственно, вопрос: как получить/преобразовать введенные параметры и работать с ними как с обычными char-символами?
(через std::string/std::wstring вкупе с c_str() не получилось %))
Заранее спасибо.
8 ответов
240
21 мая 2009 года
aks
2.5K / / 14.07.2006
Исходя из вышенаписанного std::basic_string<_TCHAR> является соотвественно или std::string или std::wstring — в зависимости от настроек юникодности проекта (макросов типа UNICODE).
Исходя из вышенаписанного std::basic_string<_TCHAR> является соотвественно или std::string или std::wstring — в зависимости от настроек юникодности проекта (макросов типа UNICODE).
Это тоже пробовал, вот в таком ключе:
#ifndef UNICODE
typedef std::string String
#else
typedef std::wstring String
#endif
но почему то не заработало, и даже тип не переопределился, т.е. объявление String myString; считается ошибкой.
настройки IDE чтоли поковырять надо? тогда какие:)? пробовал и на бесплатном visual c++ 2008 express и на полной visual studio 2008 — результат аналогичный
//—————————————————
или я не правильно понял? и std::basic_string<_TCHAR> — это тип, для хранения строки и в него надо передавать параметры(и т.д. обрабатывать их)?
240
21 мая 2009 года
aks
2.5K / / 14.07.2006
Это тоже пробовал, вот в таком ключе:
#ifndef UNICODE
typedef std::string String
#else
typedef std::wstring String
#endif
но почему то не заработало, и даже тип не переопределился, т.е. объявление String myString; считается ошибкой.
Значит где то в коде ошибка или это объявление не видно или синтаксическая ошибка где то.
и std::basic_string<_TCHAR> — это тип, для хранения строки и в него надо передавать параметры(и т.д. обрабатывать их)?
std::basic_string — это стандартный шаблонный класс для строк. Собственно он параметризуется символьными типами char и wchar_t и в результате получаются такие тайпдефы как std::string и std::wstring.
_TCHAR — это тоже char или wchar_t в зависимости от настроек и потому параметризовав им получим эти строковые типы.
Я во всем вышеописанном разобрался, но конечной цели так и не достиг.
В целях проверки делаем код(константа UNICODE определена!):
#include «stdafx.h»
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t buf1[5];
buf1[1] = argv[1];
char buf2[5];
buf2[1] = argv[1];
return 0;
}
соот-но в 1м случае получаем ошибку: невозможно преобразовать ‘_TCHAR *’ в ‘wchar_t’
а во 2м: невозможно преобразовать ‘_TCHAR *’ в ‘char’
(объявляя указатели wchar_t *buf1; char *buf2; результат такой же)
То есть _TCHAR и не в char, и не в wchar_t не преобразовывается %)
Не понимаю, в чем же я ошибся…
3
22 мая 2009 года
Green
4.8K / / 20.01.2000
Не мучай себя и окружающих
Напиши просто
int main(int argc, char* argv[])
А в параметрах проекта укажи multibyte.
То есть _TCHAR и не в char, и не в wchar_t не преобразовывается %)
Не понимаю, в чем же я ошибся…
1. _TCHAR — это не тип, а макрос и он не «преобразовывается», а «раскрывается».
2. Подумай хорошенько какой тип у argv[1], а какой у buf1[1] и buf2[1]. Только хорошенько подумай.
Не мучай себя и окружающих
Я бы и рад, да вот не получается
2. Подумай хорошенько какой тип у argv[1], а какой у buf1[1] и buf2[1]. Только хорошенько подумай.
argv[1] — _tchar
buf1[1] — wchar_t
buf2[1] — char
насколько я понял в зависимости от значения UNICODE _tchar интерпретируется либо как wchar_t, либо как char. но на деле это не работает…
касательно: int main(int argc, char* argv[])
тоже пробовал(wchar_t* argv[] в том числе), введенные параметры в ascii никак не превращаются,
а вот по поводу настройки проекта можно поподробней? уже не 1й раз слышу что что-то надо в настройках поменять, но что менять и где — не говорят:)? что за мультибайт и где он лежит?
3
22 мая 2009 года
Green
4.8K / / 20.01.2000
Неправильно!
argv[1] — THAR*
насколько я понял в зависимости от значения UNICODE _tchar интерпретируется либо как wchar_t, либо как char. но на деле это не работает…
Ты правильно понял и это прекрасно работает.
а вот по поводу настройки проекта можно поподробней? уже не 1й раз слышу что что-то надо в настройках поменять, но что менять и где — не говорят:)? что за мультибайт и где он лежит?
Project Property -> General Configuration -> Character Set -> Use Multi-byte Character Set
ха-ха) «а ларчик просто открывался»
действительно argv[1] — типа tchar*,
а это значит, что (char* argv) и (char* argv[]) разные определения,
поэтому абракадабра и получалась при неправильном обращении.
а аскии/юникод тут не при чем.
Green, благодарствую. Вопрос исчерпан
#define UNICODE
#define WINVER 0x502
#include <stdio.h>
#include <windows.h>
#include <tchar.h>
int _tmain( int argc, TCHAR* argv[] ) {
if ( argc > 1 && lstrcmpi( argv[1], L"install" ) == 0 ) {
printf ( "In installn");
}
else if ( argc > 1 && lstrcmpi( argv[1], L"uninstall" ) == 0 ) {
printf ( "In Uninstalln" );
}
else if ( argc > 1 && lstrcmpi( argv[1], L"start" ) == 0 ) {
printf ( "In Startn" );
}
else {
printf ( "In else partn" );
}
return 0;
}
The above code doesnt detect the command line arguements and always prints the «else» part.
How to achieve what I intend to??
Am using «MINGW».. In windows XP..
thanks..
Deanna
23.8k7 gold badges71 silver badges155 bronze badges
asked May 18, 2012 at 13:47
9
I think MINGW compiler dont define wmain altough UNICODE is defined. In your checking code use rather CommandLineToArgvW.
Ps: sorry for my English
answered May 18, 2012 at 16:33
XearinoxXearinox
3,2262 gold badges24 silver badges38 bronze badges
- Forum
- General C++ Programming
- ‘_TCHAR’ has not been declared
‘_TCHAR’ has not been declared
|
|
When i tried to compile it is showing an error like system is not declared in the scope and ‘_TCHAR’ has not been declared
To my knowledge,
_tmain()
and
_TCHAR
are non-standard Microsoft extensions.
Try using
main()
and
char
instead, as in:
int main(int argc, char *argv[])
Topic archived. No new replies allowed.