c++ - 有没有办法让 C++ 从 cin 中接收未定义数量的字符串?

标签 c++ string user-interface cin

我试图让用户输入适当数量的单词(大约 10-20 个),然后解析输入,但使用下面的代码将等待用户为 every 字符串。

有没有办法让 C++ 自动用空字符或类似的东西填充剩余的字符串,这样输入的单词数量少于最大值就不会导致阻塞?

代码:

#include <iostream>
#include <string>

int main()
{
  std::string test1;
  std::string test2;
  std::string test3;
  std::cout << "Enter values\n:";
  std::cin >> test1 >> test2 >> test3;
  std::cout << "test1: " << test1 << " test2: " << test2 << " test3: " << test3 << std::endl;
}

最佳答案

要读取(和存储)未知数量的空格分隔字符串,您需要存储每个字符串。以一种灵活的方式提供可以无限添加(直到您的可用内存限制)的存储的最基本方法是使用字符串 vector 。字符串为每个字符串提供存储, vector 容器提供了一种将任意数量的字符串收集在一起的简单方法。

您的字符串 vector (vs)可以声明为:

#include <iostream>
#include <string>
#include <vector>
...
    std::vector<std::string>vs {};

std::vector提供 .push_back() 成员函数以将元素(在本例中为 string)添加到 vector 中,例如

    std::vector<std::string>vs {};
    std::string s;

    while (std::cin >> s)
        vs.push_back(s);

它简单地读取字符串 s 直到遇到 EOF,并且每个读取的字符串都使用 vs.push_back(s) 添加到字符串 vector 中;

总而言之,您可以这样做:

#include <iostream>
#include <string>
#include <vector>

int main (void) {

    std::vector<std::string>vs {};
    std::string s;

    while (std::cin >> s)  /* read each string into s */
        vs.push_back(s);   /* add s to vector of strings */

    for (auto& w : vs)     /* output each word using range-based loop */
        std::cout << w << "\n";

}

示例使用/输出

$ echo "my dog has fleas" | ./bin/readcintostrings
my
dog
has
fleas

检查一下,如果您还有其他问题,请告诉我。

关于c++ - 有没有办法让 C++ 从 cin 中接收未定义数量的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58495487/

相关文章:

android - 从ndk中的jni方法调用另一个C++方法

java - JInternalFrame 和键绑定(bind)

c++ - 在字符串中搜索模式

java - 如何使用多个填充段格式化 Java 字符串

java - char[] 无法转换为 String

javascript - 在 javascript 的正则表达式中传递变量以进行字符串匹配

html - CSS/HTML 导航栏问题

ios - 对于每行有两个卡片单元的 UI,哪种布局更好?

const 类型的构造函数初始值设定项的 C++ 正确输入验证

c++ - C++ Boost 库中的链接错误