D33wakar 36 Posting Whiz in Training

hi i think i got the wrong logic

pls. see my code below:

.DATA
	VAR WORD DUP(?)
    mm db 13, 10, "Enter a digit: $"
	m1 db 13, 10, "Enter string: $"
	m2 db 13, 10, "Reverse string is: $"

I only said to declare a word variable

var dw ?

not an array of words

VAR WORD DUP?

Take a look at this.

D33wakar 36 Posting Whiz in Training

You may need to reread his posts and try to understand the format of the file.

And have you understood the format of the file yourself? if so, do you mind explaining it to me.(since OP doesn't seem to interested in explaining that, he has got his own problems).

Your code is woefully inadequate.

I was just trying to explain the OP how to handle multi-dimensional arrays there.That was supposed to be a base code for his program.

I believe this bit of code will take care of the first line of the array, but how do i get the next lines. I think I need to have this in while loop because when i get to the words at the end, each word will temporarily go into the buffer so i can send it to a function that finds the word which i have yet to write.

DO you even try to compile your code before posting here?
Have you read everything there is to know about arrays?
From the way you have written your code, I don't think so.
I'm not trying to be rude here but if you haven't, read it first.

D33wakar 36 Posting Whiz in Training

As Gerard said earlier ,

Once it reaches 127(the character variable) the value will wrap around to the lowest values which is -128.

so this will happen with your code.
when i becomes127 (for the first time);

while(i<=127)

since it satisfies the loop.
will go inside and prints the value of i(=127).

printf("%d\n",i);

then increases the i by 1

i+=1;

.
but since the character value can not be greater than 127, it wraps around to the lowest value which is -128 in case of char.
hence i=-127
Now again the loop will check the condition

while(i<=127)

since it satisfies the loop condition(-128 is smaller than 128)
it will go in and prints the value of i.
and again add 1 to it.consequently i=-127.
In this way the value of i cycles from 1 to 127 becomes -128
again from -128 to 127 becomes -128 and so on.
hence the loop will never terminate.

D33wakar 36 Posting Whiz in Training

First of all, you're using the if statement in the wrong way(a semicolon before the body)

if (t != NULL);
{
printf("%s\n",line);// here you should use "t" instead of "line"
 
 
 
}

Strtok separates the string in tokens separated by a delimiter string (here " "). Printing the "t" will print the first token at first.

fgets (line, sizeof (line), fp);
char* t=strtok(line," ");
if (t != NULL)
    printf("%s\n",t);

calling strtok for the second time (with NULL as the first argument if you're reading from the same string) will print the second token and so on.If there are no tokens left it will return NULL.

fgets (line, sizeof (line), fp);
char* t=strtok(line," ");/*in the first call the first argument should not be NULL*/
if (t != NULL)
    printf("%s\n",t);
t=strtok(NULL," ");
if (t != NULL)
    printf("%s\n",t);
t=strtok(NULL," ");
if (t != NULL)
    printf("%s\n",t);

So to achieve the output you want you have to do like this:

...
if (fp == NULL)
    perror ("error opening file");
else {
    while(fgets (line, sizeof (line), fp)){
        t=strtok(line," ");
        printf("\n");
        while( t != NULL ) {
            printf( "%s\t",t);
            t = strtok( NULL, " " );
        }
    }
}
...
Ancient Dragon commented: good info +17
D33wakar 36 Posting Whiz in Training

You can do that like this:

setterm -bold on

--> bold mode on

setterm -bold off

-->bold off
try:

man setterm

or

info setterm

for more information.

D33wakar 36 Posting Whiz in Training

since fgets will not do what you're trying to do:

while(fgets(inarray,sizeof(inarray),stdin) !=NULL)

Because fgets reads the chars in to "an array", and you're giving the address of "three" arrays ((3X3) means array of 3 arrays of chars) to it.
You can easily read chars in to the array with getchar() , no need to use fgets() (unless you've been explicitly told to ).
This example may help you.

#include <stdio.h>
/*based on your example illustration
A B C                           
E F G                             
H I J
*/
int main(void){
    char inarray[3][3];
    int i=0,j=0,c;

    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
            inarray[i][j]=(char) getchar();

    for(i=0;i<3;i++)
        for(j=0;j<3;j++)
            printf("%c",inarray[i][j]);

return 0;

}
D33wakar 36 Posting Whiz in Training

Thanks for the bad reps WaltP! You're awesome!

D33wakar 36 Posting Whiz in Training

From your question above I only managed to understand that, you want to display all the files with '.c' and '.txt' extensions in the current directory . Am I right?
if so then you can do like this in bash:

ls *.c *.txt

i.e ls filetypes. '*' is just a wildcard specifier.
If this is not what yo're looking for then you may have to elaborate your question.

D33wakar 36 Posting Whiz in Training

Do you think if I write your above code in that format would it work?

To find that out, you have to try it. and yes I forgot to mention

Correct me if Im wrong but isnt an array such a function?

Array is not a function, it's just a data type which itself is a collection of a particular data type (integers,chars,float,double etc.) and is also used for other purposes apart from handling strings.

D33wakar 36 Posting Whiz in Training

You'd better post shell scripting related kind of threads here
any way ,you can edit it like this

cat > file.txt
Hello, I am a linux user myself.
EOF

and press [ctrl]+[c] keys to save it.
And if you want to use c for that purpose.then

#include <stdio.h>
int main(){
FILE* fptr;
if((fptr=fopen("file.txt","w"))==NULL)
    return 1;
fputs("I am a linux user myself\n",fptr);
fclose(fptr);
return 0;
}

And you don't need to write the word "EOF" to make c able to know where your file ends, if that's what you're trying to do.

D33wakar 36 Posting Whiz in Training

I described the purpose somewhat in the first post. I have a .txt file which has a poem writing in it. im suppose to input that poem into the program and get it to output the poem word for word. Each word in a new line without the the punctuations or spaces that are in the poem.

Im suppose to run the program through the command prompt as so:

lab2a.exe<data.txt>output.txt

The problem with the code that I have written so far is that it only reads each letter and not each word, also it doesnt read capital letters. And like I stated before I cant use any sting handling functions other than getchar and putchar. Correct me if Im wrong but isnt an array such a function?

I hope this will help.

#include <stdio.h>
#include <ctype.h>
int main ()
{
	int c;
	printf("enter the word for format conversion:\n");
	while ((c=getchar())!=EOF){
		if(isalpha(c))
			putchar(c);
		else if(isspace(c))
			putchar('\n');
	}
	return 0;
}
D33wakar 36 Posting Whiz in Training

What's the purpose of your program? Is it just to read some characters from the console and print it out after changing its case(i.e 'a' if 'A' and 'Z' if 'z')?

As you can see if you looked at my code I use a similar loop to make it read the characters.

yeah, I see that.
But you said you can only use getchar() and putchar() but you have also used printf and scanf in your code.I'm little confused here.It would be easier if you provide the answers to these questions:
1.Are you trying to take input from console or a file.
2.You want to take input a word at a time or a whole sentence or even paragraph(s).
3.Are you trying to change the case of the characters? Lower to upper or upper to lower or both?
4.And what's with the "poem" thing?

Can I put that in my newpoem function?

Yeah go ahed. No one's gonna stop you.

D33wakar 36 Posting Whiz in Training

1) What do I need in a function to take a whole word?

using getchar() , you're gonna have to put it in a loop, like this:

while((c=getchar())!=EOF)

and save it to an array to form the complete word.

2) How do I print each word in a new line?

putchar('\n')

after each word.

D33wakar 36 Posting Whiz in Training

You should post it in the python forum and yes try to be explicit about your problem(even including your code
if you have to), that way you'll get what you're looking for much faster.

D33wakar 36 Posting Whiz in Training

I AM USING TURBO C To Write This Programe

I think You should get another compiler, may be pelles C or Code::Blocks or any other, whichever you like and feel comfortable to use.

@gerard4143 sir i am a starter pizz make it correct

If you're a starter ,IMHO you should start with something small.In this code you're just making some general syntax errors like gerard pointed out earlier- using colons instead of semi-colons,or using braces when there is no need of it or using it the wrong way

else
}
par=ptr;
ptr=ptr->left;
}

etc.

WaltP commented: And by getting a 'better compiler' he fails the class. Great idea! :( -4
D33wakar 36 Posting Whiz in Training

of course you can.

Addsign db '+','$'

or

Addsign db 2Bh

--> 2Bh being hex value of '+' in ascii character set.

In this way:
char ascii(hex)
'-'----->2Dh
'*' ---->2Ah
'/'----->2Fh

D33wakar 36 Posting Whiz in Training

Sure.one way to do it is, put the whole program in an infinite loop and ask the user each time whether to continue or not. Check the user's answer
if yes loop back
else end the loop and exit.

D33wakar 36 Posting Whiz in Training

Obviously because you're reading each string from the file saving into a variable and printing newline('\n') after each one.

printf("%s\n",name);

Don't you think this :

if(feof(fp))
break;

is unnecessary since the while statement already checks the condition and in addition it's preventing the last string from being printed out.
Also don't forget to close the file after finish using it

fclose(fp);

.

D33wakar 36 Posting Whiz in Training

This thread might clear things up.

D33wakar 36 Posting Whiz in Training
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,d,e,f,g,h,i,j,sume,sumo;
printf("Enter 10 integers: \n");
scanf("%d%d%d%d%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f,&g,&h,&i,&j);

I had written this far. I really do not know what to do next about only adding the inputted odd or even integers. :D I thank you for not giving the code and teaching me.

modulus? really? but i don't know how the modulus can display the remainder? and also the code for it. :(

instead declare an array of integers.

#include <stdio.h>
#include<conio.h> // don't use it, there's no need of it and is not portable

int main(void) {// main should always return int

int numbers[10];//an array of 10 integers
int i;
printf("enter 10 integers separated by space or newline\n");
for(i=0;i<10;i++){
    scanf("%d",&numbers[i]);
}
return 0;
}
D33wakar 36 Posting Whiz in Training

diwarak wagle, what do you mean by while(1) in your program

It is same as writing while(true) It causes the loop to execute infinetly or unless the break; statement is encountered(as you can see in the above code) .

D33wakar 36 Posting Whiz in Training

I think

fflush(stdin);

will result an undefined behavior so you better use getchar() after the last scanf()(see line 28 in the above code).

...
scanf("%s",&choice);
getchar();
...
D33wakar 36 Posting Whiz in Training

sorry I was wrong about the infinite loop thing. It seems that you did ask for the "choice"(was hard to read without formatting tags).
This should work.

#include <stdio.h>

int main()
{
float result, number2;
int x;
char operation,choice,r,R;
result = 0.0;

printf("the calculator has started.\n");
while (1){
	printf ("result is %lf\n",result);/* the format specifier for the double type is %lf*/
        fflush(stdin);
	scanf ("%c%f",&operation,&number2);

if (operation == '+')
	printf ("%f\n", result+=number2);// result= result + number2
if (operation == '-')
	printf ("%f\n", result-=number2);
if (operation == '*')
	printf ("%f\n", result*=number2);//result = result * number2
if (operation == '/')
	printf ("%f\n", result/=number2);//result = result / number2
if (operation == 'r'||'R')
	printf ("final result: %f\n",result);

printf ("do you wish to continue y/n?\n");
scanf ("%s", &choice);
if (choice =='n')
	break;

}

return 0;
}
D33wakar 36 Posting Whiz in Training

First of all ,put your code between the code tags (see that "

" thing just above your message editor box), it'll make easier to read for all of us and even you.

[code]

#include <stdio.h>
int main(void)
{
//your code
return 0;
}

use while instead of

do while

and then see how things go.
you never ask for the "choice".

if (choice =='n')
{break;}

Where did the 'n' come from.That you just wrote is a 'infinite loop' since "choice" is never equal to 'n'.
You never ask for the numbers to perform operations on , how will the user know what the input should be?

D33wakar 36 Posting Whiz in Training

that extra word variable will i declare in the data segment?

yep.Though it can be declared in code segment also but we rather keep things simple here.

when i take input, does that mean am gonna use 01h?

yeah that's right. I said "char by char"(means one character at a time) remember!

D33wakar 36 Posting Whiz in Training

I have used getchar() to take the input instead of scanf beacause it looked very messy and probably is unsafe too(the way you're handling the whole array with the magical scanf() and it's %s format specifier).
I've also used a function to keep the switch statement simple and more readable. exit() is just a function defined in stdlib.h library to exit the program right away.

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

void binop(void);



int main()

{

unsigned choice;

	do
	{
	printf("Enter an Operation?\n");
	printf("Yes(1) or No(2)\n");
	scanf("%u", &choice);
	}while (choice < 1 || choice > 2);

switch(choice){
	case 1: //case 1
		binop();
		break;



	case 2://case 2
	printf("goodbye");
	break;
}

return 0;

}

void binop(void)
{
	int i, num1=0, num2=0, num3=0,sum=0;
	int str1[8],op, str2[8], str4[8];
	int str3[8]={128,64,32,16,8,4,2,1},c;

	printf("Enter the first binary number: ");
	fflush(stdin);
	for(i=0;i<8;i++){
		c=getchar();
		if(c>'1' || c<'0')
			exit(1);//not binary , handle anyway you like
		str1[i]=c-48;
	}

	printf("Enter the next binary number: ");
	fflush(stdin);

	for(i=0;i<8;i++){
		c=getchar();
		if(c>'1' || c<'0')
			exit(1);//not binary , handle anyway you like
		str2[i]=c-48;//convert to ascii
	}

	printf("enter the operation to perform:");
	fflush(stdin);
	op=getchar();



	for (i=0;i<8; i++){
		num1=(str1[i]*str3[i])+num1;//Convert Binary into integer so i can do arithmetic

		num2=str2[i]*str3[i]+num2;
	}

		if (op=='+')
			num3=(num1+num2);//do the arithmetic on the converted binary number
		if(op=='-')
			num3=(num1-num2);
		if(op=='*')
			num3=(num1*num2);
		if(op=='/')
			num3=(num1/num2);
       printf("%d in decimal\n",num3);




	for(i=7;i>-1;i--){//convert it back into binary
            if(i-1==0 && (num3/2)>1){
                printf("overflow!\n");
                exit(1);
            }
            str4[i]=num3%2;
            num3=num3/2;
	}
	for(i=0;i<8;i++)
            printf("%d",str4[i]);

}
D33wakar 36 Posting Whiz in Training
if(str1[i]=='1');

This code is read by the compiler like

if(str1[i]== '1')
    ;//[I]Do Nothing [/I]
num1=(num1 + 0);//[I]outside the branch condition [/I]

and also

for (i=0; i<=7; i++)
 
if(str1[i]=='1'); //This is where there is problems
num1=(num1+str3[i]); //Convert Binary into integer so i can do arithmetic
if(str1[i]=='0');
num1=(num1 + 0);
 
 
if (str2[i]=='1');
num2=(num2+str3[i]);
if(str2[i]=='0');
num2=(num2+0);

the for loop statements should have curly braces if they have body with multiple statements.

for(i=0;i<=7;i++){
    /* loop body */
}

Same rule goes with your switch statement

switch(expression){
    case 1:
    /*do something*/
    break;

    
    case 2:
    /*do something*/
    break;
}

I think you should go through the first few chapters(upto the discussion of the loop statements) of your favorite C Programming book and then come back later and try to deal with this code.
There are some issues with your algorithm too but we'll deal with them later.

D33wakar 36 Posting Whiz in Training

The address passed to scanf() will be the same

I was only discussing language specifications not implementations but I should admit I didn't know about the 'undefined behavior' in the above case.I'm glad you clarified what to use and what to not.

This is a very subtle error that rarely manifests as a real problem, so beginners tend to have a hard time understanding it.

Not if they bang their heads more often.Am I right?

The latter is undefined behavior because it's not the expected type for the %d format specifier.

But I don't get it. Why don't they(those who standardize C and even the compiler manufacturers) take care of this 'undefined behavior' thing. I guess this is one of the main reasons why C is hard to grasp and is even considered as a "dangerous programming language".

D33wakar 36 Posting Whiz in Training

There are tons of syntax errors here. Did you try to compile your code?
1.You have not #included stdlib.h file(system() is defined in stdlib.h).
Are you using that to clear the screen? I think you should avoid doing that.As some people say, you have no right to own the console.
2.In your for statement.

for (i==0; i<=7; i++) //this is where the problem is

'==" is not an assignment operator.It compares the left and right operands for equality.
it should be

for(i=0;i<=7;i++);

The same thing applies to your 'if' statements too.
3.In line 32

scanf("%d", &str3[i]);

You have already initialized the array str3

int str3[8]={64,32,16,8,4,2,1};

and again you're trying to save a(God knows what) value to each of them.

scanf("%d", &str3[i]);

I hope this will help.

D33wakar 36 Posting Whiz in Training

Now you're gonna have to show some effort here.

How can i allow for multidigit?

You can do it youself if you have understood my code.
hints:
-> declare an extra word variable
-> take input, char by char and save it in the new word variable.
-> use it as counter, like my example code.

D33wakar 36 Posting Whiz in Training

thnx...bt then why we take & while using integer type of array?

consider example given by asitmahato.

int b[10]
 
scanf("%d",b);//b is also the base address of the array .

It is same as writing:

int b[10]
scanf("%d",&b);//gives 'address of' b,(the zeroth place)
printf("%d\n",*(arr));//prints the 'value at address" zero of array b

moreover

int b[10],i;
for(i=0;i<10;i++)
    scanf("%d",&b[i]);//gives 'address of' b starting from zeroth to ninth place

We can do same thing with arrays of char also

char b[5];
scanf("%c",&b);
printf("%c\n",*(b));

Was that clear enough?

D33wakar 36 Posting Whiz in Training

thanks. after i put the printing code, what should i do to get the number of the byte that the program should display?

If you mean to take a single digit(i.e. the user will be able to enter at most nine characters only).
then here's how :

get_limit:
	mov ah,01h	;get the input
	int 21h
	xor ah,ah	;ah = 0
	sub al,48d	;convert to decimal from ascii
	mov cx,ax	;cx=the digit you entered
	mov si,ax	;also copy it to si(used afterwards)

Even if you want to handle "multidigit" number, you can use this as a base code.It would be a good exercise.

Now print your prompt and read the characters:

;print second message
	mov dx,offset m1;copy the address to dx
	mov ah,09h      ;display
	int 21h

read_string:
	mov ah,01	;take input
	int 21h
	push ax		;save it in the stack
	dec cx		;decrease counter
	cmp cx,0        ;if limit reached
	je write_string	;jump to write_string
	jmp read_string	;loop

And then finally print it in reverse.
In the code you wrote above-

display1:
mov ah, 02h
pop dx
int 21h
loop display1
 
mov ah, 4ch
int 21h

you have not mentioned when to stop,so the program will go on printing and probably crashes thereafter.
Here's a modified version of that.

write_string:
	mov dx,offset msg3	;print the third message
	mov ah,09h
	int 21h
	

display1: 
	pop dx		;finally display the string in reverse
	mov ah,02h		
	int 21h
	dec si		;decrease the counter(cx was copied to si,remember!)
	cmp si,0        ;finished printing? 
	je …
D33wakar 36 Posting Whiz in Training

I found it myself.Here's the corrected code.

get_num:		;(function get_num: read integers from stdin)	
	push ax		;save all registers		
	push bx
	push cx
	push dx
	mov bx,10d	;bx=10(decimal)
	xor dx,dx			
GNloop1:xor ax,ax
	mov ah,01h	;get the input from stdin
	int 21h
	xor ah,ah	;ah all clear!
	cmp al,0Dh	;check if the input was <return>
	je GNloop2	;if yes then goto GNloop2
	cmp al,08h	;check if BACKSPACE was pressed
	jne _continue_	;if not, then continue
	
	xor ax,ax       ;otherwise ...	
	mov ax,tmp	;take the value in tmp(a word variable) and-
	sub ax,cx	;remove what was entered just before the backspace
	push ax		;save it in stack,it'll be restored in dx afterwards
        xor dx,dx       ;empty dx first 
        div bx		;ax=ax/10       
	mov tmp,ax	;and save to tmp
        cmp ax,0	;if it was first digit
	jz GNloop1	;then carry on
	pop dx		;if not first digit , then don't forget- 
			;to restore what was in dx before backspaced digit      
	
	
	jmp GNloop1	;and then jump back.
	
_continue_: 
	sub al,48d	;convert from ascii to decimal,ascii value of 0 is 48d(i.e. 30 in hex)
	xor cx,cx	;cx=0
	mov cl,al	;save al in cl(used when implementing BACKSPACE)
	add ax,dx	;add (ax*10=)dx and ax,in first loop dx is Zero,hence ax=ax+0
	xor dx,dx	;dx=0
	mov tmp,ax	;save what's in ax to tmp (a word variable),
			;1st loop:digit in ones place,2nd loop: digit in tens place... 
	mul bx		;ax=ax*10
	mov dx,ax	;save ax*10 in dx(it will be added to ax in next loop-
			;see two instructions above) 
	jmp GNloop1	; loop

GNloop2:pop …
D33wakar 36 Posting Whiz in Training

What the..?
Is'nt this the right forum?
I think I should download gimp after all.

D33wakar 36 Posting Whiz in Training

I wrote a procedure to read integers(unsigned) from stdin and store it in a variable.

I wanted it to handle backspaces too. so I made some adjustments but unfortunately it didn't work.--see line 14 in the code

get_num:		;(function get_num: read integers from stdin)	
	push ax		;save all registers		
	push bx
	push cx
	push dx
	mov bx,10d	;bx=10(decimal)
	xor dx,dx			
GNloop1:xor ax,ax
	mov ah,01h	;get the input from stdin
	int 21h
	xor ah,ah	;ah all clear!
	cmp al,0Dh	;check if the input was <return>
	je GNloop2	;if yes then goto GNloop2
	cmp al,08h	;check if BACKSPACE was pressed
	jne _continue_	;if not, then continue
	
	xor ax,ax       ;otherwise ...	
	mov ax,tmp	;take the value in tmp(a word variable) and-
	sub ax,cx	;remove what was entered just before the backspace
	push ax		;save it in stack,it'll be restored in dx afterwards
	div bx		;dx=ax/10
	mov tmp,dx	;and save to tmp 
        cmp dx,0	;if it was first digit
	jz GNloop1	;then carry on
	pop dx		;if not first digit , then don't forget- 
			;to restore what was in dx before the(backspaced) digit was pressed
	
	
	jmp GNloop1	;and then jump back.
	
_continue_: 
	sub al,48d	;convert from ascii to decimal,ascii value of 0 is 48d(i.e. 30 in hex)
	xor cx,cx	;cx=0
	mov cl,al	;save al in cl(used when implementing BACKSPACE)
	add ax,dx	;add (ax*10=)dx and ax,in first loop dx is Zero,hence ax=ax+0
	xor dx,dx	;dx=0
	mov tmp,ax	;save what's in ax to tmp (a word variable),
			;1st loop:digit in ones place,2nd loop: digit in …
D33wakar 36 Posting Whiz in Training

Alright, here's the deal.There's a folder with Jpg images and I want to open each JPG image in that folder, rotate it clockwise once and save it with the same name in the same folder.
How do I do that with batch programming?
We Can't use "Windows Picture and Fax viewer" for this right?

D33wakar 36 Posting Whiz in Training

I can tell because main() uses implicit int, which was removed in C99.

Even though compilers supporting c99 features(E.g. LCCwin32->that's what I'm using right now) give warnings if int is omitted before main().
"no type specified.Defaulting to int. "

Also while compiler language extensions are on and warning level is set to max,
using

int main()

gives warnings like
"old-style function definition for 'main'."
"missing prototype for 'main'"

That was not the case with

int main(int argc,char* argv[])

though( cause I was running out of 'main' definitions.)

D33wakar 36 Posting Whiz in Training

It's because of this line

int a[n];

You cannot declare arrays like that.
Here either 'n' should be initialized prior to declaring array

printf("Enter size:");
scanf("%d",&n);
int a[n];

or n should be replaced by some constant value.
like this:

#define BUFFER 100
...
int a[BUFFER];
challarao commented: Thank you +2
D33wakar 36 Posting Whiz in Training

Your code should start at 100h instead of 0, right?
Is there a preprocessor directive to tell it to ORG 100h?

That hex(48) at offset 0C is the 'H' in the string, so that part is OK.

Did you mean to include ORG 100h in the .code segment?
Well, I did that but nothing much happened.
But the problem's soved now .I was missing

mov ax,@data
mov ds,ax     ;ds points to .data

Thanks anyways.

D33wakar 36 Posting Whiz in Training

I will see if I can get masm or tasm and see what's going on with the .DATA

This works using the a86 compiler.

.MODEL small 
	.STACK 100h		; defines a stack 100h (256) bytes long 
	.DATA 
	.CODE 

Start:  mov dx,offset String	; point dx to the storage location for the first character
        mov ah,9		; dos function for string  output
        int 21h

Stop:   mov ax,4C00h		;exit dos 
           int 21h 
String  DB "Hello World!",'$'	; variable declaration 
END Start

I'm using masm16 assembler.
Here's what the debug utility showed:

-u
0B80:0000 BA0C00        MOV     DX,000C
0B80:0003 B409          MOV     AH,09
0B80:0005 CD21          INT     21
0B80:0007 B8004C        MOV     AX,4C00
0B80:000A CD21          INT     21
0B80:000C 48            DEC     AX
0B80:000D 65            DB      65
0B80:000E 6C            DB      6C
0B80:000F 6C            DB      6C
0B80:0010 6F            DB      6F
0B80:0011 20576F        AND     [BX+6F],DL
0B80:0014 726C          JB      0082
0B80:0016 64            DB      64
0B80:0017 2124          AND     [SI],SP
0B80:0019 47            INC     DI
0B80:001A 182A          SBB     [BP+SI],CH
0B80:001C E4A9          IN      AL,A9
0B80:001E FD            STD
0B80:001F FF7404        PUSH    [SI+04]

The DX points to address 000C which contains the code DEC AX ,but I thought the string starts from addr 000D .
Then I dumped it which gave the following:

0B80:0000  BA 0C 00 B4 09 CD 21 B8-00 4C CD 21 48 65 6C 6C   ......!..L.!Hell
0B80:0010  6F 20 57 6F 72 6C 64 21-24 47 18 2A E4 A9 FD FF   o World!$G.*....

Here you can see the first character "H" in corresponds to the 48 in hex dump.
So what's …

D33wakar 36 Posting Whiz in Training

Put a colon : after the label string
String:

That seems to make matters worse.

hello.asm(5): error A2108: use of register assumed to ERROR
hello.asm(5): error A2008: syntax error : DB

I don't think "string" is a label here(it is a string variable) so there should not be any colon following it.

D33wakar 36 Posting Whiz in Training
.MODEL small 
	.STACK 100h		; defines a stack 100h (256) bytes long 
	.DATA 
	
String  DB "Hello World!",'$'	; variable declaration 
	.CODE 

Start:  mov dx,offset String	; point dx to the storage location for the first character
        mov ah,9		; dos function for string  output
        int 21h

Stop:   mov ax,4C00h		;exit dos 
           int 21h 
END Start

The output of this program is:

I♦K☺I♦V☺I♦I♦☺☺☺ ☻               <♣Φ ë♣¶ ↑ w♣        ♣               ═!╦
                                                 ║♀ ┤      ═!╕ L═!Hello World!

What am I missing here?Can anyone help me?

D33wakar 36 Posting Whiz in Training

What does your "garbage value" look like?

like this: ¼ @

D33wakar 36 Posting Whiz in Training

I'm Using fwrite to print the contents of a sturcture in a file.

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

struct com{
           int code;
           char* name;
          };

int main()
{
struct com py[2]={{21,"Monty Python"},
		  {22,"Python lang"}
                 };
FILE * fp;
if((fp=fopen("data.txt","w+"))==NULL)
    exit(1);
fwrite(&py,sizeof(struct com),1,fp);
/*int i;
for(i=0;i<2;i++)
    fprintf(fp,"code:%d,name:%s\n",py[i].code,py[i].name);
*/
fclose(fp);
return 0;

}

It either prints nothing or prints some garbage.
While the second method using fprintf() seems to work.

D33wakar 36 Posting Whiz in Training
while((chr=fgetc(txt_file))!=EOF)
{
    if(chr==*(substring+i) || isspace(chr)||ispunct(chr))
    {
        if(isspace(chr)||ispunct(chr))
        {
            flag=1;
            continue;
        }
        
        if(flag)
        {
            i++;
            chr_match++;
        }
        
        if(chr_match==strlen(substring) && flag)
        {
            flag=0;
            if(isspace(ch=fgetc(txt_file)) || ispunct(ch=fgetc(txt_file)))/* there must be something wrong here*/
                word_match++;
        }

    }
  
    else
        i=chr_match=flag=0;

}

I'm almost there, there's a small problem in line 20 in above code.The second part of the condition ispunct(ch=fgetc(txt_file)) is not effective at all.
It was kind of a intuitional you know( it may look ridiculous).

D33wakar 36 Posting Whiz in Training

Alright, here's the code(incomplete) that I managed to write after seeing Adak’s algorithm.

...
while((chr=fgetc(txt_file))!=EOF)
    {
        if(chr=='\n')/* NOT REQUIRED*/
            continue;
        else if(chr==*(substring+i))
            {   
                i++;
                chr_match++;
                if(chr_match==strlen(substring))
                word_match++;
            }
        else
            i=chr_match=0;
    }
...

I still need to check if the words found are valid.I'm thinking of using fseek() to check if the char before and after the word is space or punctuation.What's your take on that?

Any way, I was amazed to see that the code doesn't have "splitted word" problem(Works fine without line 4 ). How come?

D33wakar 36 Posting Whiz in Training

Why?

Yeah, for that see previous posts in this thread.

What hurdles?

uh.. same answer.

D33wakar 36 Posting Whiz in Training

Then it's better not to use fgets at all.
I think it's okay to read " char by char " than to go through all the hurdles
using fgets.

#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;
}

It works fine as my requirements(up until now).

D33wakar 36 Posting Whiz in Training

Ff the target word is found, you can do the rest of your code to handle the target word being found, and then simply break out of the searching loop.

If you want to find the target word 5 times, just break out when the counter == 5.

Seems quite straight forward.

No, that's not what I meant.
I need the program to find a "word", that is string between spaces or punctuation signs . Such as,
"I ask for multitasks"--> what I want.
"I ask for multitasks"--> what the program does.


There's another problem using fgets.

while(fgets(sentence,25,txt_file) )

The above code reads 24 chars into the array. And It's not always necessary that "sentence" ends up getting space or newline all the time as the last byte.
For example:

writing the code for dra
wing shapes in the
window.

If the search word was "drawing", it would return "Not Found"

D33wakar 36 Posting Whiz in Training

Using fgets.

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


int main()
   {
	   FILE *txt_file;
	   const char* substring ="in";/*search word*/
	   int word_match=0,l=strlen(substring);


	   char sentence[25];/*to save the line read from the file)*/


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

	   while(fgets(sentence,sizeof(sentence),txt_file) )
		   {
			   /*printf("%s\n",sentence);/*testing! testing!*/
			   char* r_string=strstr(sentence,substring);


			   if(r_string!=NULL)
                              {
                                 word_match++;
                              }
                    }


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

strstr returns every string that matches the substring.
For example, here I searched for the word 'in' and it returned all the strings containing the characters 'in'.
Though, this may be compulsory in some cases (searching DNA sequences for example),
it is little bit annoying while searching for a "word" in a text.

WaltP commented: Fix your formatting!!!!! -4