捕获STDIN

时间:2010-11-29 14:50:59

标签: c++ svn

创建subversion repo时,会将许多钩子模板文件放入文件系统。在检查示例precommit hook时,它详细说明了钩子是由参数传递的信息执行的,看起来也是STDIN。

# ... Subversion runs this hook by invoking a program
# (script, executable, binary, etc.) named 'pre-commit' (for which
# this file is a template), with the following ordered arguments:
#
#   [1] REPOS-PATH   (the path to this repository)
#   [2] TXN-NAME     (the name of the txn about to be committed)
#
#   [STDIN] LOCK-TOKENS ** the lock tokens are passed via STDIN.

捕获参数是微不足道的,但程序如何捕获STDIN?在int main(...)中运行的以下代码片段无法收集任何内容。

char buffer[1024];
std::cin >> buffer;
buffer[1023] = '\0';

我做错了什么?

1 个答案:

答案 0 :(得分:5)

逐行读取的最简单方法是以下范例:

std::string line;
while(getline(line, std::cin)) {
    // Do something with `line`.
}

它也是安全,可靠和相对有效的。不要不必要地使用char缓冲区。