简体   繁体   English

c ++在动态数组中解析getline

[英]c++ parse getline in dynamic array

I already asked, how I can parse single words from a stream into variables, and that works perfectly, but I don't know how many words the user will give as input. 我已经问过,我如何将流中的单个单词解析为变量,并且完美无缺,但我不知道用户将输入多少单词。 I thought I could parse it into a dynamic array, but I don't know where to start. 我以为我可以把它解析成动态数组,但我不知道从哪里开始。 How can I write "for each word in line"? 我如何写“为每个单词排队”?

This is how I parse the words into the vars: 这就是我将这些单词解析为变量的方法:

string line;
getline( cin, line );
istringstream parse( line );
string first, second, third;
parse >> first >> second >> third;

Thanks! 谢谢!

EDIT: Thanks to all of you, I think I get it know... and it works! 编辑:感谢大家,我想我知道了...它的确有效!

You could use std::vector<std::string> or std::list<std::string> -- they handle the resizing automatically. 您可以使用std::vector<std::string>std::list<std::string> - 它们会自动处理调整大小。

istringstream parse( line ); 
vector<string> v;
string data; 
while (parse >> data) {
  v.push_back(data);
}

A possibility would be to use std::vector with istream_iterator : 可能的方法是使用带有istream_iterator std::vector

#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::istringstream in(std::string("a line from file"));

    std::vector<std::string> words;
    std::copy(std::istream_iterator<std::string>(in),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));

    return 0;
}

The vector will grow as required to store whatever number of words is provided by the user. vector将根据需要增长以存储用户提供的任何数量的单词。

You can write as follows: 您可以写如下:

string line;
getline( cin, line );
istringstream parse( line );
string word;
while (parse >> word)
    // do something with word

Since you tagged the question with foreach , here's a way to do it with with standard for_each algorithm and C++11 lambdas: 由于您使用foreach标记了问题,因此使用标准的for_each算法和C ++ 11 lambda来实现此方法:

#include <string>
#include <sstream>
#include <iostream>
#include <algorithm> // for for_each
#include <vector>    // vector, obviously
#include <iterator>  // istream_iterator
using namespace std;

int main()
{
    string line;
    vector<string> vec;
    getline(cin, line);

    istringstream parse(line);

    for_each(
        istream_iterator<string>(parse),
        istream_iterator<string>(),

        // third argument to for_each is a lambda function
        [](const string& str) {
             // do whatever you want with/to the string
             vec.push_back(str);  // push it to the vector
        }
    );
 }

A vector is exactly what you asked for - a dynamically resizable array that you should almost always prefer over C-style arrays. vector正是您所要求的 - 一个动态可调整大小的数组,您几乎总是喜欢C风格的数组。 It's size need not to be known at compile time. 它的大小不需要在编译时知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM