有没有一种方法可以使C ++从cin中获取未定义数量的字符串?

问题描述 投票:0回答:2

我试图让用户输入适当数量的单词(大约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;
}
c++ string user-interface cin
2个回答
0
投票

您可以使用while循环。类似这样的事情

string s;
while (cin >> s) {
    cout << s << endl;
}

或取一个字符串向量并进行一会儿,在while循环中输入并把它们推入向量。


0
投票

要读取(并存储)空白数量未知的空白字符串,您需要为每个字符串存储。最灵活的存储方式(可以无限增加(不超过您的可用内存限制))提供存储的最基本方法是使用字符串向量。字符串为每个字符串提供存储,向量容器提供了一种将任意数量的字符串收集在一起的简便方法。

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

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

[std::vector提供.push_back()成员函数,以将元素(在这种情况下为string)添加到向量,例如

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

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

[简单地读取字符串s直到遇到EOF,然后使用vs.push_back(s);将每个读取的字符串添加到字符串向量中。

完全可以将其放入:

#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

仔细检查,如果还有其他问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.