C ++ command line from text file

I would like to take the numbers from the .txt file and enter them through the command line into a program similar to the example below. I run 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];
}
+4
source share
3 answers
cout << argv[1];

is equivalent to:

char* arg = argv[1];
cout << arg;

It just prints the value of the first argument in the program

In your case, you did not provide an argument to the program.

When you use

./program < input.txt 

the content input.extbecomes stdinyour program. You can handle this 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);
} 
+3
source

You can do it:

./program $(cat input.txt)

This is a trick.

For example, if input.txt has numbers separated by spaces:

33 1212 1555

:

./program $(cat input.txt)  

33 .

+2

argv, , ..

./program 23 45 67

For. / Program <input.txt you need to read cin (standard input).

#include <iostream>
using namespace std;
int n;
int main()
{
   cin >> n;
   cout << n;
}
+1
source

Source: https://habr.com/ru/post/1539862/


All Articles