4

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

3 Answers 3

3
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);
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Because fgetc and fputc are really C++. Yeah, sure, whatever.
Any idea how I could get the value into a variable instead of printing it?
2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.