2011-12-09 64 views
11

可能重复:
How to split a string in C++?分割字符串转换成C中的阵列++

我有数据的输入文件,并且每个行是一个条目。在每一行中,每个“字段”由一个空格“”隔开,所以我需要按空格分隔行。其他语言有一个称为分裂(C#,PHP等)的功能,但我无法找到一个用于C++。我怎样才能做到这一点?这里是我的代码得到的行:

string line; 
ifstream in(file); 

while(getline(in, line)){ 

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

} 

回答

20
#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::getlinestd::ifstream像我一样。看起来你写了using namespace std在你的代码中被认为是不好的做法。所以,不要做:

+0

你能否提供一个链接来讨论为什么使用'using namespace x'是不好的做法? – jli

+0

@jli:添加了链接到我的答案。看见。 – Nawaz

+2

@Nawaz谢谢,看看我的其他问题,我正在使用的语法以及我从uni的教师那里学习C++的方式非常可疑:S !!!!! –

0

无论是从您的ifstream使用stringstream或阅读令牌通过令牌。

要与字符串流做到这一点:

string line, token; 
ifstream in(file); 

while(getline(in, line)) 
{ 
    stringstream s(line); 
    while (s >> token) 
    { 
     // save token to your array by value 
    } 
} 
+0

当然,如果您愿意,或者其他STL函数可以使用boost来复制出stringstream,那么可以使用boost。 – jli

+0

如果输入以空白结尾,则此内部while循环会在最后生成一个附加的空令牌。惯用的C++'while(s >> token)'不。 – Cubbi

+0

这是真的。也可以编辑以使用该方法。 – jli

3

尝试strtok。在C++参考中查找它:

+3

'strtok'是一个C库的东西,而海报正在问如何用C++正确地做到这一点。 – jli

+2

和C++不是c?(...... OMG所有这些年来他们都对我撒谎:D)。因为当C库已经停止在C++中工作(或转向不正确)? – LucianMLI

+0

如果混合使用,则会增加不必要的依赖性等问题。 – jli

3

我写了一个函数来模拟我的需求。 可能是你可以使用它!

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) 
{ 
    std::stringstream ss(s+' '); 
    std::string item; 
    while(std::getline(ss, item, delim)) 
    { 
     elems.push_back(item); 
    } 
    return elems; 
} 
1

下面的代码使用strtok()分割一个字符串转换成令牌和在载体中存储该令牌。

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

using namespace std; 


char one_line_string[] = "hello hi how are you nice weather we are having ok then bye"; 
char seps[] = " ,\t\n"; 
char *token; 



int main() 
{ 
    vector<string> vec_String_Lines; 
    token = strtok(one_line_string, seps); 

    cout << "Extracting and storing data in a vector..\n\n\n"; 

    while(token != NULL) 
    { 
     vec_String_Lines.push_back(token); 
     token = strtok(NULL, seps); 
    } 
    cout << "Displaying end result in vector line storage..\n\n"; 

    for (int i = 0; i < vec_String_Lines.size(); ++i) 
    cout << vec_String_Lines[i] << "\n"; 
    cout << "\n\n\n"; 


return 0; 
}