Hey guys, I am in the process of a program that counts integers I can do this by looking for the int keywork and then incrementing a variable although if an integers are implemented as:

int j,k,l;

I am not sure how to count this as 3 ints, I know I will need some form of loop that reads until the next comma and ends at the semicolon.

I have come up with the following code but it doesn't work and I was just wondering where I went wrong? Thanks.

char array [200];
ifstream file;

file.open(filel); 

	if (file.is_open()) 

	{
             while (file.getline( array, sizeof(array) ))
	          {
                       	if ( strstr ( array, "int" ) != 0 )
			{
				fint++;
                          for (i =0; i <sizeof(array)  ; i++

                            if (array[i]==',')
                                 fint++
				if (array[i]==';')
                                 break;
                           }
             }

here is one way to do it. It just has the string hard-coded, but you should be able to easily make it work with data file. Also assumes int is at the beginning of the string -- you should be able to change it to recognize int in the middle of the string too.

int main( void )
{
    string line = "int a,b,c,d; double k;";
    string tmp;
    int pos;
    if( line.substr(0,4) == "int ")
    {
        line = line.substr(4);
        pos = line.find(';');
        if(pos > 0)
           line = line.substr(0,pos);
        int counter = 0;
        while(line != "")
        {
           int pos = line.find(',');
           if(pos < 0)
           {
              tmp = line;
              line = "";
           }
           else
           {
               tmp = line.substr(0,pos);
               line = line.substr(pos+1);
           }
           counter++;
           cout << counter << ": " << tmp << endl;              
               
        }    
    }
    cin.ignore();
  return 0;
}

Hi I managed to get the above code working but if two ints appear on the same line like:

int j; int k; the second will be ignored I have tried to use a pointer to solve this but it has not worked any advice on where I went wrong would be great thanks.

char array [200];
ifstream file;

char * ch = array;

file.open(filel); 

	if (file.is_open()) 

	{
             while (file.getline( array, sizeof(array) ))
	          {
                       	if ( (ch=strstr ( array, "int" )) != 0 )
			{
				fint++;
                               ch++
                          for (i =0; i <sizeof(ch)  ; i++

                            if (ch[i]==',')
                                 fint++
				if (ch[i]==';')
                                 break;
                           }
             }

your program will not work if there is a variable name that contains the string "int" but is not an int data type. Example: "float myint". your program will see myint as the int. you need to check for a space following int -- "int ", and also check for a space preceeding or beginning-of-line. example: "float myint " is not what you want even though there is a space following text "int".

Thanks, I have to use arrays for this code but with the strstr function if i use "Int " it will bring up the wrong number of ints.

If you have time could you please update where I have went wrong with the piece of code so it will be able to work and then that will give me a great idea of what else I will be able to do using arrays in this way.

Thanks.

how did you test that?

int main( void )
{
    char line[] = "int a,b; int c;";
    char*p = strstr(line,"int ");
    cout << p << endl;
    p = strstr(&line[1],"int ");
    cout << p << endl;
    cin.ignore();
  return 0;
}

or using strtok

int main( void )
{
    char line[] = "int a,b; int c;";
    char *str = strtok(line,";");
    while(str)
    {     
       char*p = strstr(str,"int ");
       cout << p << endl;
       str = strtok(0,";");
    }
    cin.ignore();
  return 0;
}

>> for (i =0; i <sizeof(ch) ; i++

ch is a pointer, so sizeof(ch) will ALWAYS return 4 (assuming a 32-bit compiler). what you want is length of the string -- using strlen(ch)

Im kind of confused now does the code you posted, take care of both the "float myint" pproblems i see how it takes care of the first one by checking for a space after the int but im not sure how it deals with the problem of "float myint "

Thanks again for your help

int main( void )
{
    char line[] = "int a,b; int c;";
    char *str = strtok(line,";");
    while(str)
    {     
       char*p = strstr(str,"int ");
       cout << p << endl;
       str = strtok(0,";");
    }
    cin.ignore();
  return 0;
}

No -- I did not post a solution, just mentioned it as something YOU need to consider. I left the solution up to the programmer (you!)

Thanks for your help would you mind giving me more of a hint towards the "float myint " problem as I can't figure it out.

I am also not sure what the following line of code does.

p = strstr(&line[1],"int ");

I can 't figure this out I even tried reading until white space but that won't work either because of the whitespace search "float myint "

while (file >> array)
{
 if ( (ch=strstr ( array, "int" )) != 0 )
 {

>> I can 't figure this out

Didn't your mother ever tell you that can't never did anything? try a little harder, and don't expect to do it all in one line of code. After getting pointer from strstr, check the character just before it to see if it is either the beginning of the line or a space. If it is neither, then it isn't the "int" keyword.

char *ptr = strstr(line,"int ");
if(ptr != 0)
{
  if( ptr == line || isspace(*(ptr-1)))
  // if ptr is at beginning of line, or previous character
  // is a white space
  {
         // int keyword found
  }
}

Thanks for your help that was very cleaver coding, im not sure of the syntax: isspace(*(ptr-1))) but I am going to look into that in more detail.

I am still having the problem that if two ints are declared on the same line i.e. int j; int k; the second one will be ignored I have tried to use a pointer to keep track of the place in the array for example

char *ptr = strstr(line,"int ");
char *aptr = strstr(aptr,"int ");

if(ptr != 0 && aptr !=0)
{
  if( ptr == line || isspace(*(ptr-1)))
  {
         // int keyword found
        aptr++//increment pointer
  

      for (int i =0; i < sizeof(line) ; i++) 
	{
		if (line[i]==',')	
               {							                          
                 
                    //count an int
                  aptr++;//increment pointer
                }

                if (fileWord[i]==';')		
                 {							             
                    break;
                }
     }

one way to do it is to use strtok() to split the original string up with the semicolon. Then use strstr() in the pointer returned by strtok(). That way you only have to work with one statement at a time.

*(ptr-1) does nothing more than back up the pointer one character and reference the char at that location.

Hi thanks for you help I am just wondering how come the following code doesn't work for two words for example james smith, I have been trying all day to get it to work this way but have had no luck?

char *ptr = strstr(line,"james smith ");
if(ptr != 0)
{
  if( ptr == line || isspace(*(ptr-1)))
  // if ptr is at beginning of line, or previous character
  // is a white space
  {
         //james smith found
  }

works for me -- what makes you think it isn't working?. And, BTW, main always returns int, never void. I know some older textbooks and some M$ examples use void main() that that is incorrect.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	char line[] = "james smith and son";
	char *ptr = strstr(line,"james smith ");
	if(ptr != 0)
	{
		if( ptr == line || isspace(*(ptr-1)))
		// if ptr is at beginning of line, or previous character
		// is a white space
		{
			 cout << "Found" << endl;
		}
		else
			cout << "Not found" << endl;
	}
}
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    char line[] = "james smith and son";
    char *ptr = strstr(line,"james smith ");
    if(ptr != 0)
    {
        if( ptr == line || isspace(*(ptr-1)))
        // if ptr is at beginning of line, or previous character
        // is a white space
        {
             cout << "Found" << endl;
        }

        for (i =0; i <sizeof(line)  ; i++
                {
                            if (line[i]==',')
                                 js++;
                if (line[i]==';')
                                 break;
                }
    }
}

The only difference with my code was it has a for loop. Still not working for some reason

Edited 3 Years Ago by Dani: Formatting fixed

The only difference with my code was it has a for loop. Still not working for some reason.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	char line[] = "james smith and son";
	char *ptr = strstr(line,"james smith ");
	if(ptr != 0)
	{
		if( ptr == line || isspace(*(ptr-1)))
		// if ptr is at beginning of line, or previous character
		// is a white space
		{
			 cout << "Found" << endl;
		}

		for (i =0; i <sizeof(line)  ; i++
                {
                            if (line[i]==',')
                                 js++;
				if (line[i]==';')
                                 break;
                }
	}
}

Yeah it does seem to work when I tried it with your code, I will go through mine line by line until I figure out what was wrong.

for (i =0; i <sizeof(line)  ; i++

The above ^^^^ is wrong, use strlen(line) instead because sizeof(line) may not be the same as the string length.

char line[1024] = "Hello Word";

sizeof(line) = 1024, but strlen(line) = only 11!

Hi I have just two questions about the code below when using char *ptr = strstr(line,"james smith "); does this mean that the if statement:
if( ptr == line || isspace(*(ptr-1))) is no longer needed?

I was also wondering is the comment is correct in saying if ptr is at the beginning of the line because doesn't ptr just return a pointer to the first place it finds james smith, so how could it know if it is at the beginning of the line or not?

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	char line[] = "james smith and son";
	char *ptr = strstr(line,"james smith ");
	if(ptr != 0)
	{
		if( ptr == line || isspace(*(ptr-1)))
		// if ptr is at beginning of line, or previous character
		// is a white space
		{
			 cout << "Found" << endl;
		}
		else
			cout << "Not found" << endl;
	}
}

Hi I have just two questions about the code below when using char *ptr = strstr(line,"james smith "); does this mean that the if statement:
if( ptr == line || isspace(*(ptr-1))) is no longer needed?

what about the string "mrjames smith" ? will you accept a pointer to that too? If not, then that code is still needed.

I was also wondering is the comment is correct in saying if ptr is at the beginning of the line because doesn't ptr just return a pointer to the first place it finds james smith, so how could it know if it is at the beginning of the line or not?

not certain what you are asking, but if ptr == line, then ptr is pointing to the first character in line. This is testing the address of ptr and line, not comparing the two strings.

what about the string "mrjames smith" ? will you accept a pointer to that too? If not, then that code is still needed.

Hi for that example I would not use a pointer so does that mean that the code: if( ptr == line || isspace(*(ptr-1)))
would then ignore that string? and wouldn't it do this anyway without the line of code. (sorry im a bit confused)

not certain what you are asking, but if ptr == line, then ptr is pointing to the first character in line. This is testing the address of ptr and line, not comparing the two strings.

Ah i see I was getting confused I thought it pointed to the first instance of james smith and not the start of the line so if there was something in the string before james smith for example "his name was james smith" it wouldn't be the start of the line.

Ah i see I was getting confused I thought it pointed to the first instance of james smith and not the start of the line so if there was something in the string before james smith for example "his name was james smith" it wouldn't be the start of the line.

That's the purpose of if( ptr == line) -- to see if ptr starts at the beginning of the line or somewhere in the middle, as in your example. But in the string "his name was mrjames smith", the check *(ptr-1) == ' ' will not be true because the character just befor the 'j' in 'james' is 'r', not a space.

Thanks for that, I have used similar code to search for FOR loops how ever if someone writes a for loop like the following with no whitespace after the for:
for(int k=0; k<10; k++)

I thought I would need another if to searh for "for(int" but for some reason the code does what i need anyway and for some reason i dont even need the second lot of if statments below which check for "for(" it will still find it even though there is no whitespace after the for. Can you please tell me why this is the case? Thanks

char *ptr =array;

	if(ptr = strstr(ptr, "for "))
	{
	   if(ptr == array || isspace(*(ptr-1)))
												
	    {
		ptr++;
									
		return true;
		}
    }
							
		ptr = array;

		if(ptr = strstr(ptr, "for("))
			{
		          if(ptr == array|| isspace(*(ptr-1)))
										
				{
					ptr++;
									
						return true;
					}
                    }
This article has been dead for over six months. Start a new discussion instead.