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?
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.
Use wcout for Unicode strings.
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.
Related
I am attempting use ifstream to extract two numbers from a file in argv[1], named "inputFile", and the extracting operator seems to be extracting the bits of code rather than the numbers needed.
inputFile.txt was put into the command line operator by right clicking the project, going to properties -> debugging -> command arguments -> typing inputFile.txt into command arguments in visual studio 2017.
The file inputFile.txt is as below:
1 2
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[])
{
//Test opening file
cout << "Input file: " << argv[1] << endl;
ifstream in(argv[1]);
if (!in)
{
cerr << "Unable to open " << argv[1] << " for input";
return 1;
}
//extract numbers
int num1;
int num2;
in >> num1 >> num2;
cout << num1 << endl << num2 << endl;
in.close();
return 0;
}
I expect the int num1 to hold 1, and the int num2 to hold 2, but instead each variable holds the number -858993460.
Are you sure the file you are reading has got the data you expect? This code works fine for me, compiling with Visual Studio 2005. But, If I change the contents of the file, writing not numbers (for example if I write: a b), num1 and num2 ends with -858993460.
I have two processes: t1.cpp and t2.cpp.
t1.cpp and t2.cpp are simplified ,I want to describe the problem easily.
//t1.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "hello\n"
<< "world\n"
<< "ok ok\n";
return 0;
}
//t2.cpp
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string str;
while(getline(cin,str)){
cout << str <<endl;
}
//cin.clear();
//flush the cin
//cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
char x;
cin >> x;
return 0;
}
After compiling t1.cpp and t2.cpp. I execute them in this way ./t1 | ./t2.
Problems occur! cin >> x; in t2.cpp failed! I have no chance to type from the keyboard.
It seems the pipe command implements by redirecting the STDIN_FILENO. Does it forbid the standard input simultaneously?
My harsh requirements is obtain data from the output of t1 with shell command |,in addition,I want interact with users in t2.For example,I would display Sure to del?[y/n],and wait users's anwser.
Actually, there is something you can do in the C++ code. t1 has to read from stdin and echo that to stdout, which is redirected. You can do something like this at various places:
T value;
std::cin >> value;
std::cout << value;
Or to emulate the behaviour of the shell command in the comments (append stdin after t1 has finished writing its data to stdout):
std::copy(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout));
Finally,we deal this problem using "/dev/tty"
FILE *file = fopen("/dev/tty","r");
if(NULL == file){
/*error*/
}
int ch = fgetc(file);
if('y' == ch || 'Y' == ch){
/*balabala*/
}
when stdin or stdout was redirected , we also can read or write from the /dev/tty.
I have the following console app in Visual Studio
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
wcout << "displayStringsTest_data" << endl;
wcout << L"列举" << endl;
wcout << "Done" << endl;
return 0;
}
But the Chinese characters are output as question marks
Does anyone know how I can get them output in the correct form
Thanks
Even though you are sending correct Chinese symbols to console.
Windows setting should be changed so that it supports those language specific characters.
You need to change PC language to Chinese from "Region and Language" section from control panel, which is by default to US English.
command line arguments having null after each char suppose i call the program from the command prompt like "abc.exe test data" then in memory there is an space after each char and the data is "t.e.s.t..d.a.t.a" What is the issue.
It is printing t only the first char not the complete string "test"
What is the issue.
int _tmain(int argc, _TCHAR* argv[])
{
printf("The number of Argc %d %s",argc,argv[1]);
return 0;
}
You are using UNICODE encoding (see the _t prefix in _tmain and _tchar).
This encoding stores characters on 2 bytes.
Hence you should use _tprintf instead of printf.
Can you help me understand the following code?
void errorexit(char *pchar) {
// display an error to the standard err.
fprintf(stderr, pchar);
fprintf(stderr, "\n");
exit(1);
}
Calling errorexit("Error Message") will print "Error Message" to the standard error stream (often in a terminal) and exit the program. Any programs (such as the shell) that called your program will know that the there was an error since your program exited with a non-zero status.
It is printing out the string pointed to by pchar to the standard error output via fprintf and then forcing the application to exit with a return code of 1. This would be used for critical errors when the application can't continue running.
That function prints the provided string and a newline to stderr and then terminates the current running program, providing 1 as the return value.
fprintf is like printf in that it outputs characters, but fprintf is a little different in that it takes a file handle as an argument. I this case stderr is the file handle for standard error. This handle is already defined for you by stdio.h, and corresponds to the error output stream. stdout is what printf outputs to, so fprintf(stdout, "hello") is equivalent to printf("hello").
exit is a function that terminates the execution of the current process and returns whatever value was its argument as the return code to the parent process (usually the shell). A non-zero return code usually indicates failure, the specific value indicating the type of failure.
If you ran this program from the shell:
#include <stdio.h>
#include "errorexit.h"
int main(int argc, char* argv[])
{
printf("Hello world!\n");
errorexit("Goodbye :(");
printf("Just kidding!\n");
return 0;
}
You'd see this output:
Hello world!
Goodbye :(
And your shell would show "1" as the return value (in bash, you can view the last return code with echo $?).
Note that "Just kidding!" would not be printed, as errorexit calls exit, ending the program before main finishes.