在c ++中使用unix shell中的文本文件时,如何请求用户输入?

Equ*_*uay 1 c++ unix shell file mips

我运行我的代码a.out < file.txt,当我尝试cin >> variable用来询问用户输入时,我读取了所有文件.

Ton*_*roy 5

当您调用程序时a.out < file.txt,您要求shell将file.txt内容作为标准输入来管道,a.out 而不是让键盘提供标准输入.如果不适合你,然后添加一个命令行参数来指定文件名,使用的ifstream将其打开,从而不是阅读cin,使用cin的键盘输入.

例如:

int main(int argc, const char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " <filename>\n";
        exit(1);
    }
    const char* filename = argv[1];
    if (std::ifstream in(filename))
    {
        // process the file content, e.g.
        std::string line;
        while (getline(in, line))
            std::cout << "read '" << line << "'\n";
    }
    else
    {
        std::cerr << "unable to open \"" << filename << "\"\n";
        exit(1);
    }
    // can still read from std::cin down here...
}
Run Code Online (Sandbox Code Playgroud)