1

for example:

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

here parsing is used so what can b used in c for doing this?

Kanha
  • 43
  • 1
  • 6

3 Answers3

3

Here is an example code that is your snippet translated to 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;
}

Update I changed the calls of strtok to strtok_r as recommended by Adam Rosenfield in the comments.

halex
  • 16,253
  • 5
  • 58
  • 67
  • `strcmp` returns 0 on success. This won't work as intended by OP. – P.P Oct 05 '12 at 20:37
  • @KingsIndian Thanks. Typed faster than I thought :) Edited. – halex Oct 05 '12 at 20:39
  • 1
    Keep in mind that `strtok` is not thread-safe or reentrant (in the case of signals) due to its reliance on global static data. On POSIX systems, consider instead using [`strtok_r`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtok.html). – Adam Rosenfield Oct 05 '12 at 20:56
  • and also please explain that strtok is not thread safe how?and what it means? – Kanha Oct 06 '12 at 09:42
1

If you are doing something non-trivial, think of using flexand bison.

doron
  • 27,972
  • 12
  • 65
  • 103
0

Something like this?

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;
}
Stewart
  • 4,356
  • 2
  • 27
  • 59
  • 1
    much to complicated. `strtok` is what you need. Besides, `p == "hello"` is a pointer comparision. To compare string you use `strcmp` – Pablo Oct 05 '12 at 20:32