从未知长度的手动输入中提取单个单词

Pulling individual words from manual input of unknown length

本文关键字:提取 单个单 手动输入 未知      更新时间:2023-10-16

重新发布,因为我在最后一个中没有包含足够的信息。

我尽力了谷歌fu,似乎找不到正确的答案(并不意味着这不是一个愚蠢的错误,因为我还是新手)

int main()
{
    vector<string> clauses;
    string test;
    cout << "Please enter your choice or choicesn ";
    while (cin >> test) {
        clauses.push_back(test);
    }
    return 0;
}

我不知道他们会输入多少个选项,所以我把它们扔进一个向量中。

目前,当它运行时,它不会接受任何用户输入,即使按回车键,也只是让该人继续输入。

提前谢谢。保罗

以下代码应该适用于您想要执行的操作:

#include <vector>
#include <string>
#include <iostream>
int main()
{
    std::vector<std::string> clauses;
    std::string test;
    std::cout << "Please enter your choice or choicesn";
    do
    {
        getline(std::cin, test);
        if(!test.empty())
            clauses.push_back(test);
    }while (!test.empty());
    return 0;
}

getline 函数将读取键盘上的任何文本并将其推送到您的矢量中,直到用户仅使用 Enter 键,这将结束循环。