Reputation: 483
I would like to take numbers from a .txt file and input them through the command line into a program like the example below. I run the exe using ./program < input.txt. However it prints random numbers. What am I doing wrong?
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//print 1st number
cout << argv[1];
}
Upvotes: 4
Views: 9169
Reputation: 206567
cout << argv[1];
is equivalent to:
char* arg = argv[1];
cout << arg;
It just prints the value of the first argument to the program
In your case, you didn't provide an argument to the program.
When you use,
./program < input.txt
the contents of input.ext
becomes stdin
of your program. You can process that using:
int c;
while ( (c = fgetc(stdin)) != EOF )
{
fputc(c, stdout);
}
If you want to stay with C++ streams, you can use:
int c;
while ( (c = cin.get()) != EOF )
{
cout.put(c);
}
Upvotes: 3
Reputation: 943
You can do this:
./program $(cat input.txt)
This does the trick.
For example, if input.txt has numbers separated by spaces:
33 1212 1555
Running:
./program $(cat input.txt)
prints 33 to the terminal.
Upvotes: 2
Reputation: 3049
To be able to use argv numbers need to be supplied as arguments, i.e.
./program 23 45 67
For ./program < input.txt you need to read from cin (standard input).
#include <iostream>
using namespace std;
int n;
int main()
{
cin >> n;
cout << n;
}
Upvotes: 1