2012-10-05 68 views
1

例如:在解析的情况下,可以在C中使用什么而不是istringstream(在C++的情况下)?

istringstream ss("hello hi here haha"); 
string p; 
while (iss >> p) 
{ 
    if (p == "hello") 
     statement1; 
    else if (p == hi) 
     statement2; 
} 

这里使用,因此什么可以在C B用来做这个分析?

+0

如果我理解正确,'strok'。 – chris

+0

@chris你能举一个例子代码的例子..? – Kanha

+0

如果你忽略了一些小的C++元素,[这里是一个](http://en.cppreference.com/w/cpp/string/byte/strtok)。 – chris

回答

3

下面是一个例子代码,你的代码片段转换为C:

#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char s[] ="hello hi here haha"; 
    char *tok; 
    char *last; 
    tok = strtok_r(s, " ", &last); 
    while (tok != NULL) { 
    if(!strcmp(tok, "hello")) 
     statement1; 
    else if(!strcmp(tok, "hi")) 
     statement2; 
    tok = strtok_r(NULL, " ", &last); 
    } 
    return 0; 
} 

更新我改变的strtok来电来strtok_r作为意见建议亚当罗森菲尔德。

+0

'strcmp'在成功时返回0。这不会按照OP预期的那样工作。 –

+0

@KingsIndian谢谢。键入比我想象的更快:)编辑。 – halex

+0

始终发生,+1 :) –

0

这样的事情?

char* ss = "hello hi here hahah"; 

int i=0; 
while (ss[i] != '\0') 
{ 
    while (ss[i] != ' ' && ss[i] != '\0') 
    ++i; 

    char* p[40]; 
    memcpy(p,ss,i); 

    if (p == "hello") 
    statement1; 
    else if (p = "hi") 
    statement2; 
} 
+1

复杂得多。 'strtok'是你需要的。此外,'p ==“hello”'是一个指针比较。要比较字符串,您使用'strcmp' – Pablo

相关问题