C++ 循环 I/O 问题

标签 c++ io

int main(int argc, char *argv[]) {
    while (true) {
        std::cout << "Enter command (with arguments) to profile: ";
        std::string command;
        std::cin >> command;
        std::cout << "Running command: " << command << std::endl;
        Process::create(true, command);
    }
}

这应该不是一个困难的问题,但我是一个初级 C++ 程序员。我有以下代码应该无限循环,提示并接受用户输入。然后它将输入作为命令运行到我在别处创建的函数。

问题是在输入第一个命令后,输出由 Process::create 方法打印,当循环返回时,它使用打印的数据而不是接受我自己的输入。我究竟做错了什么?我想我可能需要刷新 cin 流或其他东西,但我不知道。

这是一个示例输出来演示我的问题:

Enter command (with arguments) to profile: ls
Running command: ls
Enter command (with arguments) to profile: homework8      Homework8.cpp~  Process.cpp~    stats.dat
Homework8      plot_stats.gnu  Process.h       TestProgram.cpp
Homework8.cpp  Process.cpp     ProcessStats.h

最佳答案

使用 std::getline 从流中获取字符串,而不是 std::cin >> 命令;

std::string command;
std::getline(std::cin, command);

或者在从流中获取之前需要检查 std::cin

using std::cin;
using std::getline;

char line[MAX_LINE];    /* Line buffer */

while(true)
{
    /* Get command */
    cout << "viettuan@shell:~$ ";
    if (!cin)
        cin.clear();
    else
        cin.getline(line, MAX_LINE);

    //... Do process here
}

关于C++ 循环 I/O 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315904/

相关文章:

c++ - Visual Studio 2008 构建错误

c++ - 给每个给定的自然数分配一个随机自然数

c - 使用 fflush(FILE* stream)

c++ - 比较BGR图像是否完全相同

c++ - 函数返回类型中的 "&"符号是什么意思?

Java IO 写入时出错,但读取时不出错

linux - 如何让 printf 写入新文件、追加现有文件并写入标准输出?

我可以使用 xmlzipio 通过 xmlReadMemory 从内存中读取 xml 吗?

Haskell "do nothing"IO,或者如果没有 else

c++ - 以枚举作为模板参数从 C++ 中的模板类继承