【问题标题】:How can I cin a char with multiple words?如何用多个单词输入一个字符?
【发布时间】:2021-12-23 05:32:33
【问题描述】:

我尝试在互联网上查找,但没有看到答案。

所以我必须用多个单词来输入一个字符,例如“汽车有四个轮子”。我需要接受每一个字并找出他。我在学校了解到你可以这样做:

char a[100][20];
cin.getline(a, 100);

但它不起作用。用空格分隔多个单词的字符的正确方法是什么;

【问题讨论】:

  • this 有帮助吗?或者,如果你必须使用char 数组而不是std::string... 你确定学校说过你可以在数组数组上调用getline 吗?
  • std::string word; while (std::cin >> word) { std::cout << word << '\n'; }
  • 至于你的错误,a 是一个 of arrays 个字符的数组。而cin.getline() 需要一个字符数组。 IE。类似a[0]a[1]
  • edit 这个问题包含您正在谈论的代码和错误,作为实际文本。一旦 imgur 决定删除该图像,此问题将失去所有价值。

标签: c++ visual-studio


【解决方案1】:

您可以尝试使用std::istringstream 来解析单词。

std::vector<std::string> word_database;
std::string text_line;
while (std::getline(std::cin, text_line))
{
    std::string word;
    std::istringstream text_stream(text_line);
    while (text_stream >> word)
    {
        word_database.push_back(word);
    }
}

在上面的代码中,在text_line变量中输入了一行文本。

istringstream 是使用文本行创建的。使用operator&gt;&gt; 从文本流中提取“单词”。单词被附加到数据库中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多