简体   繁体   中英

C++ command line input from a text file

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

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.

To be able to use argv numbers need to be supplied as arguments, ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM