'How to read a .txt file from terminal, and then extract contents from file?

I am wanting to use C++ to extract the contents of a .txt file (that will be pointed to from the terminal) that is to be parsed, but I am not sure how to go about doing this? I know that we do

./a.out < file.txt

which will then put file.txt into the standard input, but then I got confused because I am not sure how to access the file contents to parse it, etc.



Solution 1:[1]

You can treat the directed input as input into cin. Say if I had the following file input.txt

Hello
World

And you run your executable like

./a < input.txt

I could do something like

std::string s1;
std::string s2;
std::cin >> s1;
std::cin >> s2;
std::cout << s1 << s2 << "\n";

Which would then print Hello Word. getline with cin is also an option here. Think of it as though a very fast user were inputting a line immediately at each of your input statements.

Solution 2:[2]

You can get the filename as input on the arguments to main, and open an std::ifstream to that file.

int main(int argc, char* argv[]) { 
    std::ifstream file(std::string(argv[1]));
    if (file.is_open()) {
        //read input
    }
}

You would call ./a filename. To read from file, you would do so as you do from std::cin (see NickLamp's answer).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NickLamp
Solution 2 Ramon