简体   繁体   中英

Read input from .txt in C++

I've got a .cpp which is prompted as follows:

$ ./program file < file.txt

Then I want to use the text on the file.txt for some functions inside my program. How can I access the input on the .txt on my .cpp?

stdin? cin? could you put some examples?

You must use std::cin

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

you can use ifstream to open your file and getline function to read it line by line. You don't need to use < to pass param to your program. The param can be get in the argv array of your main function

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