-1

I have a file with numers I am trying to open,however when I run my file it does not print the values and just gives me 0.

code:

int main(int argc,char *argv[])
{
 for (int count=0; count < argc; ++count)
    std::cout << count << " " << argv[count] << '\n';
  return 0;
 }

File:

        198      4          12

And the output I get when i run ./text < file.txt is 0.

user4581301
  • 33,082
  • 7
  • 33
  • 54
Continuum
  • 67
  • 1
  • 9
  • argv is an array of pointers to char. Length is stored in argc argument. – 0xdw Nov 02 '17 at 02:51
  • How would I go about extracting the numbers from the text file? – Continuum Nov 02 '17 at 02:52
  • You don't even get 0 ./text? The file should be going to standard in, not to the command line. – user4581301 Nov 02 '17 at 02:53
  • The file name has to go to the command line (requirement) – Continuum Nov 02 '17 at 02:55
  • Sorry. I'm unclear. if you execute ./text < file.txt then the contents of file.txt should show up in standard in and be readable with cin. More reading here: https://stackoverflow.com/questions/15680530/bash-read-stdin-from-file-and-write-stdout-to-file – user4581301 Nov 02 '17 at 02:58

2 Answers2

1

The < file.txt syntax you're using is essentially simulating keyboard input, i.e., an input stream traditionally known/accessed as std::cin in C++ or stdin in C.

More background on that topic: What are the shell's control and redirection operators?

Your code is trying to iterate over command-line arguments, which is neither pulling input from std::cin, nor is it accessing the input with any awareness that a file is involved.

If you want, or need, to extract data from std::cin (which is consistent with your < syntax), check out the following reference with examples of how that's done: std::cin, std::wcin.

If you want to process input as a file, try this reference with example: std::basic_ifstream.

(Note that this latter example deals with a binary file, but you can make appropriate changes for your text file.)

Phil Brubaker
  • 1,257
  • 3
  • 11
  • 14
0

I think you'are trying to redirect file's content to INPUT stream, try this code snippet:

#include <iostream>
#include <string>
#include <sstream>

int main(int argc, char **argv)
{
    std::string str;
    std::stringstream ss;

    while (std::getline(std::cin, str)) {
        ss << str << "\n";
    }

    std::cout << ss.str();
}
f_x_p
  • 58
  • 9