while and if, what is the difference?

Hi,

I am learning C++ and I have the following code:

//Tokenizing program: pointer version.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
  char str[80];
  char token[80];
  char *p, *q;
  
  cout << "Enter a sentence: ";
  gets(str);
  
  p=str;
  
  //read a token at a time from a string
  
  while (*p)
    {
      q=token;
  /*read a character until either a space or a null character is encounterd*/
      
      while (*p && *p!= ' ')
    {
      *q=*p;
      q++;
      p++;
    }
    if (*p)
    p++;
    *q = '\0';
    cout << token << endl;
    }
  return 0;
}

When I changed the second while statement to an if statement, as:

//Tokenizing program: pointer version.
#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
  char str[80];
  char token[80];
  char *p, *q;
  
  cout << "Enter a sentence: ";
  gets(str);
  
  p=str;
  
  //read a token at a time from a string
  
  while (*p)
    {
      q=token;
  /*read a character until either a space or a null character is encounterd*/
      
      if (*p && *p!= ' ')
    {
      *q=*p;
      q++;
      p++;
    }
      else if (*p)
    p++;
      *q = '\0';
      cout << token << endl;
    }
  return 0;
}

I started to have the output written in a vertical form, that is one letter at line.

What is the difference between the two codes?

Thanks,

faizlo

In the first example you are building a string (by looping within the while statement block until you either encounter the case where *p is a null or space character) and then outputting the string followed by a newline.

In the second example you are just examining the value of a pointer (*p) and outputting this character followed by a newline.

Hi fpmurphy,

Thanks for the reply. So, in the first case, while was looping and continues to loop till it reaches *p = ' ' or '\0'. with each step it assign its value to q, which increments also per index.

In the second case, if just spells out each character each time while (the first one) loops, right?

faizlo

Correct

Thank You fpmurphy,

faizlo