2014-11-06 248 views
0

我已经从文件中取出所有的txt并逐行放入字符串数组中。我想分割这个字符串,以便我可以单独保存在单独的数组中。请告诉我shell是如何将字符串数组转换为char的。将字符串转换为字符

例如

string line[15]; // line[0] has : was there before 
        // line[1] has : then after 

char * pch; 
char *c = line.c_str(); // string to char (i am getting error here. Any body know?) 
    pch = strtok (c," "); 
    while (pch != NULL) 
    { 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " "); 
    } 

错误:C2228:左 '.c_str' 必须具有类/结构/联合

+1

'line'是不是一个字符串。它是一串字符串。你也许可以做'line [0] .c_str()'。你还需要使用'const char * pch;'或者你会得到另一个错误。 – 2014-11-06 18:33:20

+2

'line'是一个数组。它不是'class/struct/union'。你的意思是(例如)'char * c = line [0] .c_str();'?此外,您可以编写自己的使用'std :: string'的令牌函数,而不是使用旧的c函数。 – clcto 2014-11-06 18:33:59

+0

为了加入我最后的评论,我写了一个'tokenize'函数,可以在https://github.com/clcto/utile/blob/master/src/utile.cpp行235 – clcto 2014-11-06 18:39:30

回答

2

string line[15];是一个字符串数组。所以当你有line.c_str();行是一个指向字符串的指针而不是字符串本身。指针没有.c_str()方法,这就是编译器抱怨的原因。 (指针没有任何方法,因此编译器会告诉你表达式的左边必须是类/结构/联合类型)。要解决这个问题,你需要索引到数组中以获得一个字符串。你可以这样做:line[0].c_str();

此外,你不能写回由c_str()返回的任何东西,因为它返回一个const指针。所以你需要先复制c_str的结果,然后再对它进行操作,如果你要改变它的话。

另外它可能值得一提的是,有C++的方式来做标记化,你可能会在这里找到一些例子Split a string in C++?。上次我这样做时,我已经在使用boost了,所以我使用了boost::tokenizer库。

+0

找到。通过编写char * c = line [0] .c_str();给我错误,但是当我用这种方式写char * c = line [0] .c_str;不给我错误。 (我正在使用Visual Studio 2012),这是正确的? – user3440716 2014-11-06 18:38:29

+0

@ user3440716您需要使用像const char * c = line [0] .c_str()这样的函数,因为'c_str()'是一种您需要使用圆括号的方法。 – shuttle87 2014-11-06 18:49:43

+0

通过放置const它给出错误:'strtok':不能将参数1从'const char *'转换为'char *' – user3440716 2014-11-06 18:57:25

1

在C++中有更简单的方法来实现这一点。 strtok函数是C函数,不能直接与std::string一起使用,因为无法获得对std::string中底层字符的可写指针访问。您可以使用iostream来直接在C++中获取由文件中的空格分隔的单个单词。

不幸的是,标准库缺乏简单,灵活,高效的方法来拆分任意字符上的字符串。如果您想使用iostream来完成除空格之外的其他内容,则会变得更加复杂。使用boost::splitboost::tokenizer Shuttle87的建议是一个很好的选择,如果你需要更灵活的东西(它也可能更高效)。

下面是一个代码示例从标准输入文字阅读,你可以使用几乎相同的代码与ifstream从文件或stringstream阅读从一个字符串读取:http://ideone.com/fPpU4l

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

using namespace std; 

int main() { 
    vector<string> words; 
    copy(istream_iterator<string>{cin}, istream_iterator<string>{}, back_inserter(words)); 
    copy(begin(words), end(words), ostream_iterator<string>{cout, ", "}); 
    cout << endl; 
}