将字符串拆分为C ++中的数组 [英] Split a string into an array in C++

查看:126
本文介绍了将字符串拆分为C ++中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何在C ++中拆分字符串?

Possible Duplicate:
How to split a string in C++?

我有一个数据的输入文件,每行是一个条目。在每行中,每个字段由空格分隔,因此我需要按空格拆分。其他语言有一个称为split(C#,PHP等)的功能,但我不能找到一个为C ++。我该如何实现呢?这是我的代码,获得行:

I have an input file of data and each line is an entry. in each line each "field" is seperated by a white space " " so I need to split the line by space. other languages have a function called split (C#, PHP etc) but I cant find one for C++. How can I achieve this? Here is my code that gets the lines:

string line;
ifstream in(file);

while(getline(in, line)){

  // Here I would like to split each line and put them into an array

}


推荐答案

#include <sstream>  //for std::istringstream
#include <iterator> //for std::istream_iterator
#include <vector>   //for std::vector

while(std::getline(in, line))
{
    std::istringstream ss(line);
    std::istream_iterator<std::string> begin(ss), end;

    //putting all the tokens in the vector
    std::vector<std::string> arrayTokens(begin, end); 

    //arrayTokens is containing all the tokens - use it!
}

顺便说一下,使用 std :: getline std :: ifstream 。看起来你在代码中的某处使用命名空间std 写了这被认为是一种坏习惯。所以不要这样做:

By the way, use qualified-names such as std::getline, std::ifstream like I did. It seems you've written using namespace std somewhere in your code which is considered a bad practice. So don't do that:

  • Why is 'using namespace std;' considered a bad practice in C++?

这篇关于将字符串拆分为C ++中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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