在c++中使用unix shell中的文本文件时,如何请求用户输入
How can you ask for user input when also using a text file in unix shell in c++?
我使用a.out < file.txt
运行代码,当我尝试使用cin >> variable
请求用户输入时,我读取了所有文件,但它什么也没做。
当您用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...
}
如果在stdin之后需要额外的用户输入,则必须打开名为"/dev/tty"的控制终端。示例:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream tin("/dev/tty");
ofstream tout("/dev/tty");
tin.tie(&tout);
while (true) {
string input;
tout << "> ";
getline(tin, input);
if (input == "quit")
break;
}
return 0;
}
为了说服自己,上面不会读取重定向文件,一个简单的测试:
$ echo "quit" | ./a.out
>
相关文章:
- std::getline没有在while循环中重新请求用户输入
- curl 请求的用户输入
- 如何在使用 cin 请求 int 时有效地使用户输入万无一失?
- 偶尔多次请求用户输入循环
- 处理用户的输入,这是一系列请求
- 请求用户输入,然后忽略它
- 当代码已经输入curl_easy_perform()时,如何中止网络请求
- 检查 int 的输入,如果是字符,请再次请求输入(Turbo C++)
- C++ if 语句未按预期工作,在请求输入之前打印"else"
- 整数输入 拒绝非整数输入并在C++中请求另一个输入
- 如何在嵌套循环中请求用户输入
- 如何理解C++常见问题中的"程序忽略我的输入请求"?
- 如何请求输入以一次初始化多个结构
- 如何让程序在打印出 while/if 语句之前请求输入字符串"course"
- cin.ignore()为什么请求输入
- 在c++中使用unix shell中的文本文件时,如何请求用户输入
- 请求用户输入以便重新运行程序或退出
- 可以在程序退出时和请求输入时自动刷新自定义流缓冲区
- 为什么程序要循环而不是请求输入
- 如何再次请求输入c++