C ++如何将来自stdio的输入字符串放入向量,每个容器元素一个字 [英] C++ how to put an input string from stdio into a vector, one word per container element

查看:129
本文介绍了C ++如何将来自stdio的输入字符串放入向量,每个容器元素一个字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++,我有点新手。我已经研究了这个问题了很多。我在c ++中学习过矢量,字符串和字符串流,但我仍然找不到正确的方法来做到这一点。

基本上,我想写,在命令行中的一些文本,并且将一些放入在位置0和文本的向量容器中放置在位置1的同一容器中。



我发现了很多方法可行,但没有什么只是这样做。



感谢您的帮助。

解决方案

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

int main(){
std :: string line;
std :: getline(std :: cin,line); //从cin
读取一行std :: stringstream buffer(line);
std :: vector< std :: string>话;
//将每个单词从行复制到单词
std :: copy(std :: istream_iterator< std :: string>(buffer),
std :: istream_iterator< std :: string& (),
std :: back_inserter(words));
}


I'm learning c++, and I'm a bit of a newbie. I've researched this question quite a bit. I've studied vectors, strings, and stringstreams in c++ but I still can't find the 'right' way to do this.

Basically, I want to write, "some text" at the command line and have "some" put into a vector container at position '0' and "text" put into the same container in position '1'.

I've found a lot of ways that sorta work, but nothing that just does that.

Thanks for the help.

解决方案

As per your comment:

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

int main() {
    std::string line;
    std::getline(std::cin, line); // read one line from cin
    std::stringstream buffer(line);
    std::vector<std::string> words;
    // copy each word from line to words
    std::copy(std::istream_iterator<std::string>(buffer),
              std::istream_iterator<std::string>(),
              std::back_inserter(words));
}

这篇关于C ++如何将来自stdio的输入字符串放入向量,每个容器元素一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆