0
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    cout << argv[2] << endl;
}

This is just the beginning of a program that I'm writing, but I'm already stuck. It simply reads in data from a binary file that I have saved in the same directory as this program. I compile and run the program with ./a.out < filename, and the program is just supposed to print out whatever is in the file to stdout. I tried a different way by opening the file and using getline to get the data, and the data was received perfectly. I'm just wanting to know why the first method isn't working as intended and what I can do to fix this problem.

dinotom
  • 4,498
  • 10
  • 59
  • 124
Sherbs
  • 37
  • 5

1 Answers1

0

There are a few things wrong here primarily from the confusion between arguments and the input stream.

argv contains the arguments/parameters as an array of c-strings passed into the program when it was executed and argc is the number of arguments. If you were to run ./a.out filename you should see

argc = 2
argv[0] = "/<current path>/a.out"
argv[1] = "filename"

However you run ./a.out < filename which has no parameters and a redirection. So you accessing argv[2] is undefined behavior and it seems you get the junk value "xdg_vntr=8". Unfortunately I can't adequately explain why this is your result because it is undefined and would be implementation dependent on the compiler and system.

So doing < filename tells the shell running your program to open up filename and direct it into the program's standard input stream (A.K.A. std::cin) You can send the input stream buffer directly to the output stream like so std::cout << std::cin.rdbuf();

kmdreko
  • 14,683
  • 3
  • 21
  • 41
  • Thanks for the explanation. It really helped out. I can now get the input just by doing cin >> argv[2], but now the issue is with there being a space in the text in the file. – Sherbs Apr 26 '16 at 20:06
  • You can send the input stream buffer directly to the output stream like so `std::cout << std::cin.rdbuf();`. I'll update the answer – kmdreko Apr 26 '16 at 20:09
  • getline seems to be working for me. Thank you so much for your help! – Sherbs Apr 26 '16 at 20:12
  • I'll also try that. Thank you! – Sherbs Apr 26 '16 at 20:12
  • Okay, I don't know what I did, but it looked as though getline was working. Is there any way that I can get the contents from a file and save that to a variable using rdbuf()? – Sherbs Apr 26 '16 at 20:52
  • This is starting to get into another question which looks like its addressed here: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring there are a number of solutions to reading in a file to a variable – kmdreko Apr 26 '16 at 20:59