Int tmain int argc tchar argv ошибка

0 / 0 / 0

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

Сообщений: 38

1

02.06.2015, 17:44. Показов 15955. Ответов 2


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

Добрый день!
При компилировании кода, где присутствует данная строчка
int _tmain(int argc, _TCHAR* argv[])
выдаёт ошибку:
3 IntelliSense: идентификатор «_TCHAR» не определен
Также ошибка с «stdafx.h»
#include «stdafx.h»
сама ошибка:
2 IntelliSense: не удается открыть источник файл «stdafx.h»
1 error C1083: Не удается открыть файл включение: stdafx.h:
На других компьютерах работает и ошибок нет, на моём почему-то вылазят
P.S. работаю в VS2013
Знаю, что вопрос глупый, но, может, поможете?



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

02.06.2015, 17:44

2

IBM

Заблокирован

02.06.2015, 18:04

2

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

Знаю, что вопрос глупый

Верно подмечено

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

IntelliSense: идентификатор «_TCHAR» не определен

То, что IntelliSense не смог распознать, это не ошибка. Ошибки, мешающие сборке — это ошибки компилятора.

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

_TCHAR» не определен

значит не подключен файл #include <tchar.h>
А не подключен он потому, что в дефолтных проектах он подключается в файле предкомпиллированных заголовков — stdafx.h, а по скольку у тебя:

не удается открыть источник файл «stdafx.h»

то и се ля ви.

В общем ты не весь проект скопировал на другой комп, копируй весь, включая файл stdafx.h



2



lss

940 / 868 / 355

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

Сообщений: 2,706

02.06.2015, 18:23

3

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

Решение

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

может, поможете?

Вот так измени (будет стандарт):

C++
1
int main(int argc, char* argv[])

Убери #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, благодарствую. Вопрос исчерпан :)

  • Forum
  • General C++ Programming
  • ‘_TCHAR’ has not been declared

‘_TCHAR’ has not been declared

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
#include<iostream>
#include<fstream>
#include<string>


int _tmain(int argc, _TCHAR* argv[])
{
	std::fstream file;
	std::string temp;
	double first,second,third;
	file.open("rm.txt");
	/*
	while(file.good())
	{
		std::getline(file,temp);
		std::cout<<temp<<std::endl;
	}
	*/
	while(file.good())
	{
		std::getline(file,temp);
		std::getline(file,temp);
		std::getline(file,temp);
		file>>temp;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>first;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>second;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>temp;
		file>>third;
		std::getline(file,temp);
		std::cout<<"Diagonals are : "<<first<<" "<<second<<" "<<third<<std::endl;
	}
	file.close();
	system("PAUSE");
	return 0;
}

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.

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;
}

Понравилась статья? Поделить с друзьями:
  • Int object is not iterable python ошибка
  • Indesit wiun 102 сброс ошибок
  • Indesit wiun 102 ошибки расшифровка
  • Indesit wiun 102 ошибка f08
  • Indesit wiun 102 коды ошибок мигает