Can not print out the argv[] values using std::cout in VC++

半城伤御伤魂 提交于 2019-12-02 09:01:34

问题


This is my first question on the site even though i have been coming here for reference for quite some time now. I understand that argv[0] stores the name of the program and the rest of the commandline arguements are stored in teh remaining argv[k] slots. I also understand that std::cout treats a character pointer like a null terminated string and prints the string out. Below is my program.

#include "stdafx.h"
#include <fstream>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

    cout << argv[0] << " ";
    cout << argv[1] ;

    return 0;
}

According to all the other programs I have seen over my internet search in the issue, this program should printout two strings viz. name of the program and the commandline arguement. The console window shows

0010418c 001048d6

I believe these are the pointers to argv[0] and argv[1] resp. The only commandline arguement I have is "nanddumpgood.bin" which goes in argv[1] and shows the strings correctly if I mouseover the argv[] arrays while debugging.

Whis is this happening? What am I doing wrong? I understand, arrays decay to pointers in special cases? Is this a case where it doesnt?


回答1:


I also understand that std::cout treats a character pointer like a null terminated string and prints the string out.

That's mostly correct. It works for char*, but not other types of characters. Which is exactly the problem. You have a _TCHAR*, which IS char* on an ANSI build but not on a Unicode build, so instead of getting the special string behavior, you get the default pointer behavior.

I understand, arrays decay to pointers in special cases? Is this a case where it doesnt?

argv is an array, but neither argv[0] nor argv[1] are arrays, they are both pointers. Decay is not a factor here.

The simplest fix is to use int main(int argc, char* argv[]) so that you get non-Unicode strings for the command-line arguments. I'm recommending this, rather than switching to wcout, because it's much more compatible with other code you find on the internet.




回答2:


Use wcout for Unicode strings.




回答3:


I guess you are compiling your application with the unicode compiler switch which treats all TCHAR as wchar_t. Therefore cout treats argv as an int.

Write instead

wcout << argv[0] << L" "; 
wcout << argv[1] ;

or change to Use Multi-byte character set in the Project settings/General.



来源:https://stackoverflow.com/questions/8096369/can-not-print-out-the-argv-values-using-stdcout-in-vc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!