D33wakar 36 Posting Whiz in Training

I am trying to write a program for searching strings(one at a time)in a text file.
To start things off, I wrote this one.

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

int main()
   {
	   FILE *txt_file;
	   int chr;/*char read by fgetc*/
	   int word_match=0;
	   const char* substring ="window";/*search word*/
	   int i=0;
	   char word[15];/*to save the word read from the file)*/


	   if((txt_file=fopen("text.txt","r"))==NULL)
		   {
			   printf("Can't open the file\n");
			   exit(1);
			}

	   while((chr=fgetc(txt_file))!=EOF)
		   {
			   word[i]= chr;
			   i++;
			   if(isspace(chr)||ispunct(chr))
				   {
					   word[i-1]='\0';
					  /* printf("%s\n",word);/*testing! testing!*/
					   if(strcmp(word,substring)==0 )
						   {
							   word_match++;
							}
					   i=0;
					}

					if(isspace(word[i]))
						i=0;


			}


		fclose(txt_file);
		printf("Matched words:%d\n",word_match);
		return EXIT_SUCCESS;
	}

This program has got some limitations and is very inefficient too.
I'm looking for suggestions to make it a real world string searching program.

Note:Toggle plain text and copy it somewhere else If it's too hard to read due to indention.

D33wakar 36 Posting Whiz in Training

Thanks to both of you guys for posting your codes.
pyTony‘s code works fine (except string.h is missing) and also considering issues pointed out by Narue.

I was thinking about dynamic allocation , but couldn’t figure out how to do it (especially reallocating logic) since I have no experience whatsoever. So Narue’s code taught me another new thing.

D33wakar 36 Posting Whiz in Training

That's an oversight on my part.

I got the overflow thing too but rest of it went over my head.

I've got another example here using string.

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

int main()
{
	char number[20];
	int l,i,j,flag=1;
	printf("enter the number");
	fgets(number,20,stdin);


	l=strlen(number);
	for(i=0,j=l-1;i<l/2;i++,j--)
		{
			if(number[i]!=number[j])
				{
					flag=0;
					break;
				}
		}
	if(flag)
		printf("Is Palindrome number");
	else
		printf("not a palindrome");

	return 0;
}

Here's a problem

char number[20];

How can we make it more flexible (accept larger numbers)?

D33wakar 36 Posting Whiz in Training

and what about

while(!checknum)
D33wakar 36 Posting Whiz in Training

I had done it like this,

unsigned int is_palindrome(unsigned int);
unsigned int Siz_of(int);

unsigned int is_palindrome(unsigned int num)/* checks if the number(+ve integer only) is palindrome or not*/
{

	int chknum1,chknum2=0,i,rmndr;/*here rmndr is remainder after modulo,chknum is reversed num*/


	chknum1=num; /*saving num,since it is manipulated*/

	for(i=0;i<Siz_of(chknum1);i++)
		{
			rmndr=num%10;
			num=num/10;
			chknum2=chknum2*10+rmndr;
		}


	if(chknum1==chknum2)
		return(1);
	else
		return (0);

}

unsigned int Siz_of(int n)
{  int sum = 0,i,res;
   res=n;

   if (n<=-1)
	   n=-(n);
   for(i=1;i<n;i++)
	   {
		   res=res/10;
		   sum++;
		   if(res==0)
			   break;
		}
	return (sum);
}

but pyTony's is more effiecient.I'll use that instead for sure.

for loop and the i variable are not good fit for the purpose. I suggest while instead.

I know how to use while loop but have never used it like
this way: while(i) when I write my own(though I have seen others' many times)
instead I only use while loops like
this way : while(i<3)
What does the line

while(checknum)

mean?
Does it mean that the loop will be terminated if checknum==0.

D33wakar 36 Posting Whiz in Training

I was assuming that the sizeof(int) will give the number of digits in the number,but
now I know I was wrong(It returns the size of the var in bytes).
Is there a way(builtin library functions,methods..etc.) to find the number of digits in the integer?Or I have to write a separate function for that.

D33wakar 36 Posting Whiz in Training

Here's a code to find out if the number is palindrome or not.

#include <stdio.h>

int main()
{
	int num,chknum1,chknum2=0,i,rmndr;/*here rmndr is remainder after mod,chknum is reversed num*/
	printf("enter the number");
	scanf("%d",&num);
	chknum1=num;/*saving num,since it is manipulated*/
	for(i=0;i<=sizeof(chknum1);i++)
		{
			rmndr=num%10;
			num=num/10;
			chknum2=chknum2*10+rmndr;
		}
	printf("chknum1 %d,chknum2 %d",chknum1,chknum2);
	//if(chknum1=chknum2)
		//printf("Is palindrome");
	//else
		//printf("is not palindrome.");
	return 0;
}

But it prints couple of extra zeros when the number is reversed,hence will fail to tell if the number is palindrome or not.
Can anyone tell me what am I missing?

D33wakar 36 Posting Whiz in Training

Here it is.

#include <stdio.h>
#include "sqroot.h"




double pows(double,double);
double pows_f(double,int,int);

int main()
{
	double base,num;
	char power[10];
	int num_rt,denum_rt;
	int i,j,is_rational;
	printf("enter Base followed by power\n.");
	scanf("%lf %s",&base,power);

	for (i=0;i<=sizeof(power);++i)
		{
			if(power[i]=='/')  /*rational*/
				{

					num_rt=power[0]-48;
					for(j=0;j+1<i;j++)
						{
							num_rt=num_rt*10+(power[j+1]-48);/* ascii value of character 1 is 49*/

						}
					denum_rt=power[i+1]-48;
					for(j=i+1;j+1<strlen(power);j++)
						{
							denum_rt=denum_rt*10+(power[j+1]-48);/*similar to num*/
						}

					is_rational=1;
					}
	}
	if(is_rational!=1) /* not rational*/
		{
		 num_rt=power[0]-48;
	     for(j=0;j+1<strlen(power);j++)
						{
							num_rt=num_rt*10+(power[j+1]-48);/* ascii value of char 1 is 49*/
					}
		denum_rt=1;

	}





	printf("%g ",pows_f(base,num_rt,denum_rt));


	return 0;
}

double pows(double base,double n)
{


	if(base==0)
		return(0);
	else if(n==0)
		return(1);
	else if(n>=1)
		{
			return(base*pows(base,n-1));/*for positive powers*/

			}
	else if(n<=-1)
		{

			return(1/pows(base,-n));/*for negative powers*/
				        }
	else
		printf("error!");
		return(0);



}

double pows_f(double base,int num,int denum)/* num means numerator & denum means denomenator*/
{
	double pows_ed;/* variables to store  pows(ed) value*/
	pows_ed=pows(base,num);
	return root(pows_ed,denum);
}
D33wakar 36 Posting Whiz in Training

I looked at the example there.It seems totally different case than mine.
I don't know How to use it in my code.It would be great help if you'd show me an example of it(a case like mine).

D33wakar 36 Posting Whiz in Training

Alright.Everything's fine except one thing.
I need pows_f to accept usually two arguments(sometimes three).Can we do that in C?
If I need to find out 25^13 I need to enter as pows_f(25,13,1)
Can we make the third argument optional(i.e. should be given only when required)
for e.g to find 25^13 as pows_f(25,13) only and to find 25^3/4 as pows_f(25,3,4).

D33wakar 36 Posting Whiz in Training

The above code doesn't need variable root_ed,I forgot to remove it
(man!What was I thinking).and also to use %g(scientific format).

D33wakar 36 Posting Whiz in Training

Used a code in here to produce sqrt and rest is here.

#include <stdio.h>
#include "sqroot.h"




double pows(double,double);
double pows_f(double,int,int);

int main()
{
	double base,num;
	int num_rt,denum_rt;
	printf("enter Base followed by Numerator and then Denominator\n.");
	scanf("%lf %d %d",&base,&num_rt,&denum_rt);

	printf("%lf ",pows_f(base,num_rt,denum_rt));


	return 0;
}

double pows(double base,double n)
{


	if(base==0)
		return(0);
	else if(n==0)
		return(1);
	else if(n>=1)
		{
			return(base*pows(base,n-1));/*for positive powers*/

			}
	else if(n<=-1)
		{

			return(1/pows(base,-n));/*for negative powers*/
				        }
	else
		printf("error!");
		return(0);



}

double pows_f(double base,int num,int denum)/* num means numerator & denum means denomenator*/
{
	double root_ed,pows_ed;/* variables to store root(ed) value & pows(ed) value*/

	pows_ed=pows(base,num);
	return root(pows_ed,denum);
}

pows_f(5,1,2)--->5^1/2 =2.236068
pows_f(17,3,2) = 70.092796

pretty close .

D33wakar 36 Posting Whiz in Training

Yeah thanks pyTony, I really appreciate that.Now it's crystal clear to me.

For the power of fractions like 1/2,2/3,5/2 etc:
If we had to do like pows(12,2.5)
we could do like this:- 12 ^ 5/2 can be written as (12 ^ 5)^1/2
and (something)^1/2 means sqrt of (something).
Hence we need an algorithm to find not just square root or cube root but nth root of a number.Can anyone help me with that?

D33wakar 36 Posting Whiz in Training

I do not understand why do you write negative powers so as you write instead of simple 1./pows(base, -n), even it seems to work.

I didn't understand what you're trying to say.Can you "please" show it in c code.

Now, we need to handle powers in fractions like 1/2,2/3,5/7...similarly
-1/2,-3/2,-3/7...etc.
Can anyone help me figure out the solution,
OR suggest a better algorithm.

D33wakar 36 Posting Whiz in Training

Hint: a**-1 == 1/a

yeah, that's what I did here.

double pows(double base,double n)
{


	if(base==0)
		return(0);
	else if(n==0)
		return(1);
	else if(n>=1)
		{
			return(base*pows(base,n-1));/*for positive powers*/

			}
	else if(n<=-1)
		{   n=-n;

			return((base)/pows(base,n+1));/*for negative powers*/
	        }



}

for positive value:
pows(10,22) gives 10000000000000000000000.000000
but pows(10,23) gives 99999999999999992000000.000000------>(Now, where did that come from?)
for negative value:
pows(10,-6) gives 0.000001
pows(10,-7) gives 0.000000------>(how to increase its range?)

It also doesn't work if you input
12 2.5

Yeah I'll deal with those kinda fractions later.First negative exponentiation.

D33wakar 36 Posting Whiz in Training

I trimmed the precious one a little bit and used double instead of float.

#include <stdio.h>




double pows(double,double);

int main()
{
	double num,base;
	printf("enter base followed by power.");
	scanf("%lf %lf",&base,&num);

	printf("%lf ",pows(base,num));


	return 0;
}

double pows(double base,double n)
{
    

	if(base==0)
		return(0);
	else if(n==0)
		return(1);
	else if(n>=1)
		{
			return(base*pows(base,n-1));/*for positive powers*/

			}
	



}

To make it work with negative powers I was thinking like this...

else if(n<=-1)
		{   n=abs(n);/* abs()--->#include <complex.h> */
	        
			return((base)/pows(base,n+1));/*for negative powers*/
	        }

But it doesn't work that way.Here abs(n) returns zero.
something's wrong with the implementation?what should I do then?

By the way I tried the algorithm suggested inhttp://www.catonmat.net/blog/mit-int...thms-part-two/
It worked fine (but not with long arguments) .Anyways,thanks for that pyTony.

D33wakar 36 Posting Whiz in Training

It has got MAJOR precision issues.
How do I make it accept negative "power" argument
pows(100,-2) gives nothing.

D33wakar 36 Posting Whiz in Training

Other than it doesn't work properly

yeah.I know it's not perfect.But couldn't find other bugs 'cept its smaller range.
See,that's why I posted this in discussion thread.

Or is this an ego-post?

No,this is not "an ego-post".

do you have a question?

The thing is ,I didn't came up with any while posting.
So I just posted the code(looking for advice).

%f and float n does not look integer to me, like your prompt and algorithm suggests.

I was using int(egers) before,float was used to increase it's range.
I overlooked this line

printf("enter base followed by power integer.");

while changing to float.

Also you are doing both iteration and recursion same time, chose which one.

Am I supposed to do either iteration or recursion only(i.e.no need to both)?

D33wakar 36 Posting Whiz in Training
#include <stdio.h>

float pows(float,float);

int main()
{
	float num,base;
	printf("enter base followed by power integer.");
	scanf("%f %f",&base,&num);

	printf("%f ",pows(base,num));


	return 0;
}

float pows(float base,float n)
{

	if(n==0)
	  return(1);
	else if(base==0)
	  return(0);
	else
		for(;n>=1;n--)
		{   return(base*pows(base,n-1));/*recursive*/

			}



}
D33wakar 36 Posting Whiz in Training

yep I did

>>> import distutils.sysconfig
>>> distutils.sysconfig.get_config_var('LINKFORSHARED')

and it gave nothing.

D33wakar 36 Posting Whiz in Training

I'm trying to embed python script in c in windows.

#include <Python.h>

int
main(int argc, char *argv[])
{
  Py_Initialize();
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
  Py_Finalize();
  return 0;
}

from the python documentation.
I'm compiling with Microsoft's lcc.
I'm getting following errors.

Error c:\lcc\examples\python\pyembed.c 7 undefined reference to __imp__Py_Initialize
Error c:\lcc\examples\python\pyembed.c 8 undefined reference to __imp__PyRun_SimpleStringFlags
Error c:\lcc\examples\python\pyembed.c 10 undefined reference to __imp__Py_Finalize

I added python include files in the project.But I'm not sure what to do with py27.lib or py27.dll.That may be the problem I guess.

D33wakar 36 Posting Whiz in Training

Well,this is embarrassing.I'd never thought it that way.
I was looking for a data type that can hold alphanumeric digits.
But hey that's what discussion forums are for, right?
Thanks for the help Narue.

D33wakar 36 Posting Whiz in Training

What do you think the problem is?
I know

Decimal vs. hexadecimal is a display representation, the underlying bits of corresponding values are unchanged

In the above program, the user can only enter decimal digits 0-9.
I need a code that should be able to give :
00000000000000000000000000001111 for the digit F.

D33wakar 36 Posting Whiz in Training

I'm trying to convert hexadecimal values to Binary.
I've done Decimal values to Binary up to 32 bits in this way:

#include <stdio.h>
int showbits(int);/**************function*prototype******************************/

int main()
{
unsigned int num;

printf("enter the number.");
scanf("%d",&num);

printf("%d in binary is  ",num);
printf("\n");

showbits(num);/*********************function*call********************************/

return 0;
}

showbits (int n)/******************function*definition****************************/
																				//*
{
  int i,k,andmask;

  for(i=31;i>=0;i--)
  {
     andmask = 1<<i;
     k=n&andmask;
     k==0?printf("0"):printf("1");
  }
}

Now I wan't to add hexadecimal values in it.

D33wakar 36 Posting Whiz in Training

Or You may not have specified your Include directories.
for example
C:\TC\INCLUDE

D33wakar 36 Posting Whiz in Training

I couldn't find a decent C network programming book for windows.
Can anybody help me?

D33wakar 36 Posting Whiz in Training

You may post solution in vbscript also(those who find batch obsolete).

D33wakar 36 Posting Whiz in Training

I've been trying to automate the creation of a user account with admin rights using cmd bat .

net localgroup administrators [I]account name[/I]/add

got the following error:

There is no such global user or group:[I]account name[/I]

what's the problem?

D33wakar 36 Posting Whiz in Training

I want to run a program every time windows starts with a certain user's credentials .
If i did that in bat file ,it will prompt for the user's password.How can i automate the insertion of password?

D33wakar 36 Posting Whiz in Training

You should use the -tW option something like

bcc32 -tWappname.cpp

.I use bcc55 too and this is how i compile windows apps.

Thanks for the reply but that's not the answer I was looking for.There must be workaround with Borland c++ builder.

D33wakar 36 Posting Whiz in Training

here is the code:

#define  STRICT
#include <windows.h>
#pragma hdrstop
#include <stdlib.h>
#include <string.h>

LRESULT CALLBACK _export WndProc( HWND hWnd, UINT iMessage,
                                 WPARAM wParam, LPARAM lParam );

class Main
{
public:
  static HINSTANCE hInstance;
  static HINSTANCE hPrevInstance;
  static int nCmdShow;
  static int MessageLoop( void );
};

class Window
{
protected:
    HWND hWnd;
public:
    // Provide (read) access to the window's handle in case it is needed
    // elsewhere.
    HWND GetHandle( void ) { return hWnd; }

    BOOL Show( int nCmdShow ) { return ShowWindow( hWnd, nCmdShow ); }
    void Update( void ) { UpdateWindow( hWnd ); }
    // Pure virtual function makes Window an abstract class.
    virtual LRESULT WndProc( UINT iMessage, WPARAM wParam, LPARAM lParam ) = 0;
};

class MainWindow : public Window
{
private:
    static char szClassName[14];
    // Helper function used by Paint function; it is used as a
    // callback function by LineDDA.
    static void FAR PASCAL LineFunc( int X, int Y, LPSTR lpData );
public:
    // Register the class only AFTER WinMain assigns appropriate
    // values to static members of Main and only if no previous
    // instances of the program exist (a previous instance would
    // have already performed the registration).
    static void Register( void )
    {
        WNDCLASS wndclass;   // Structure used to register Windows class.

        wndclass.style         = CS_HREDRAW | CS_VREDRAW;
        wndclass.lpfnWndProc   = ::WndProc;
        wndclass.cbClsExtra    = 0;
        // Reserve extra bytes for each instance of the window;
        // we will use these bytes to store a pointer to the C++
        // (MainWindow) object corresponding …
D33wakar 36 Posting Whiz in Training

make failed
Error: Error: Unresolved external '_main' referenced from C:\BC5\LIB\C0X32.OBJ

I got above error when trying to build one of the examples given in \BC5\examples directory.What is the cause?

D33wakar 36 Posting Whiz in Training

if you did't understand the code .once again

import threading
import time
def msg():
    print "time's up"
    time.sleep(2)#just enough to show the above msg    
    exit()
t=threading.Timer(5.0,msg)
t.start()

Since I'm not a guru myself(As u can see I'm a Newbie poster)so I'm looking for it myself.
I'll inform u if I got anything useful.

D33wakar 36 Posting Whiz in Training

You can use ' threading ' module.

import threading
import time
def msg():
    print "time's up"
    time.sleep(2)#just enough to show the above msg    
    exit()
t=threading.Timer(5.0,msg)
t.start()

But you have to figure out how to use it with Raw_input. Don't hesitate to ask.Go on.

D33wakar 36 Posting Whiz in Training

Thanks for the correction ..er.. I mean direction no suggestion.

D33wakar 36 Posting Whiz in Training

do u mean like:

import random
summy=0
keys='abcdefghijklmnopqrstuvwxyz '

for i in range(100):
    y=random.choice(keys)
    if y!='m':
        summy+=1
    elif y == 'm':
        continue
print summy
D33wakar 36 Posting Whiz in Training

I didn't understand a bit from above lines.Could you explain a bit more.. or posting your example code may help.
Also try
#coding=<utf8> at the beginning of the code
also configure your terminal or IDLE default source encoding as UTF-8.

D33wakar 36 Posting Whiz in Training

The error message says that the 'return' statement is outside the function.
What's with the line 17:
return param2+1

D33wakar 36 Posting Whiz in Training

Try this:
sys.argv[0]
or
sys.argv[-1]
that should work.

D33wakar 36 Posting Whiz in Training

Yeah but the previous code gives more promising result that the latter.
Similar to that:

from Tkinter import*
import time
class myapp(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.weeds()
        
    def weeds(self):
        self.button=Button(self,text='Button',command=self.onclick).grid()        
        self.var=StringVar()
       
        self.msg=Label(self,textvar=self.var)
        self.msg.grid()
    def onclick(self):        
        self.var.set("Running command..")
        self.msg.update_idletasks()#remember to update "idle tasks"-**
        time.sleep(1.5)            #otherwise your message waits until
        self.nest1()               #mainloop 
    def nest1(self):
        self.var.set("Still Running.")
        self.msg.update_idletasks()#**
        time.sleep(2)
        self.nest2()
    def nest2(self):
        self.var.set("Not yet.")
        self.msg.update_idletasks()#**
        time.sleep(1.5)
        self.nest3()
    def nest3(self):
        self.var.set("Finished")
        self.msg.update_idletasks()#**
        
        
        
root=Tk()
APP=myapp(master=root)
APP.mainloop()
D33wakar 36 Posting Whiz in Training

It would have been better to understand your problem if you had posted your code here.
Sure I'll help.

D33wakar 36 Posting Whiz in Training

You can do like this:

>>> b=['a','b','r','g']
>>> for c in range(len(b)):
	del b[0]

	
>>> print b

You can refer to python docs for range function.

D33wakar 36 Posting Whiz in Training

using wx python.got black bars instead of unicode characters in gui window.
[hint]:My interpreter gives error-
Unsupported characters in input

D33wakar 36 Posting Whiz in Training
def nod(n):
        c,i=0,0
        while n>0:
                c=n%10
                if c!=0:
                        i=i+1
                n=n//10
        print(i)#prints the number of digits in the given integer 'n'

how to make it able to count 'zeros'?

D33wakar 36 Posting Whiz in Training

I have Gui2exe installed already but haven't quite used it due to a problem.
The problem is - in "gui"window of gui2exe the locations for python modules does not accept the given modules separated by commas
i.e.(tkinter,zipfile,fnmatch...)
Is this the right technique ?

D33wakar 36 Posting Whiz in Training

I used py2exe to make an executable,works fine.But even for a simple app I've got 18 other files(.pyd and dlls includinf pythonxy.dll) in the dist folder.
I've heard that these files can be compressed into the executable using Gui2exe.
I have Gui2exe installed already but haven't quite used it due to a problem.
The problem is - in "gui"window of gui2exe the locations for python modules does not accept the given modules separated by commas
i.e.(tkinter,zipfile,fnmatch...)
Am i really a moron or what?!

D33wakar 36 Posting Whiz in Training

Here's an interesting story.The code managed to play the WAV files but I didn't hear any 'BEEP'.Thanks anyway man.
Gotta be working on winsound..

D33wakar 36 Posting Whiz in Training

Now here's a interesting story .The test code did manage to play the WAV files but not 'The Beep'.Anyway Beep is not my problem,but actually Beep is the only problem here.
Thanks man .Lot to do with Winsound..

D33wakar 36 Posting Whiz in Training

I've got Windows Xp SP2.I'm seeking for other options here.let me know if you have anything like that to share ,especially audio specific modules.

D33wakar 36 Posting Whiz in Training

winsound.Beep(37,10)
Your frequency of 35 hertz is below the audible range
Your duration of 10 milliseconds is too short

Try something like ...
winsound.Beep(440, 200)

Still nothing Aye.Is something wrong with my audio/speaker settings or what?
should I try other modules like pygame?
Thanks for the comment by the way.