yiyige

April 29, 2011

visiting the standard and reliable websites that provide Coach Outlet Coupons

Filed under: coach — ganqing @ 3:02 am

Are searching for mentor Outlet Coupons? If your answer is yes; then there undoubtedly are a variety of ways of availing these mentor Outlet Coupons. Just possess a fast appear at the following.

If you are in the research of mentor Outlet Coupon then there undoubtedly are a variety of ways of availing these Coupons. mentor produced bags are in fashion nowadays. Why not? The very good quality concerning the mentor Handbags and purses communicate for itself. These discount codes give opportunity towards the potential purchasers to purchase Coach Outlet the handbags and purses at reduced price. As the vast majority of us know the producer mentor is facing fierce rivalry from other agents of designers like Gucci, Vera Bradley and also a variety of others. The firm should concentrate now concerning the campaign of theses finest very good quality artist bags at seasonal discount and by providing reduced coupons.

These discount codes are generally sent towards the inbox concerning the consumers by means of e-mail. These reduced provides may be also availed by going to the standard and authentic internet sites that provide mentor Outlet Coupons.

If you are unaware concerning the treatment of searching for the internet sites that provide mentor Outlet discount codes then study this paragraph; otherwise start on directly towards the next one.

Just type any concerning the next pointed out phrases concerning the research motor you use, mentor Promotional Codes, mentor reduced Handbags or mentor Bag Coupons. You will obtain a thorough checklist on your research motor which will give you the detail concerning the internet sites that provide these coupons.

Today artist bags particularly mentor produced have develop to be considered a fashion statement. each and every lady no create a difference of any age team craves to possess these mentor purses and bags. These purses are around in a wide range of colors, sizes, shapes and designs. The leather-based applied by this firm is concerning the finest very good quality and never just is gentle but durable as well.

The bags last for a lot of years. The firm has left no space to doubt the very good quality or even the durability concerning the products. However it is astonishingly crucial that you create the purchase with additional normal caution. There undoubtedly are a variety of fake products and options getting marketed out in the marketplace using the brand of “Coach”. Only genuine bags by mentor assure durability. The fake products and options appear much more such as the authentic ones so it is not astonishingly fast to distinguish amid the two. However those people that have actually applied a genuine bag can effortlessly distinguish amid the two. Even the touch concerning the authentic and the fake bag is enough to help the smart and repeated consumers to distinguish amid the two.

Come and grab 100 percent free discount codes around at mentor Handbag Outlet. These branded bags will not just hold your appear and design but at identical time enable you to definitely avail the mentor Outlet Coupons.

October 18, 2010

Sound

Filed under: C Program — Tags: — admin @ 8:00 am

Sound


Answer:Is it possible to import sound? If so how? I dont have that much extensive knowledge. I think i may use either .wav file or a midi file. please help!!! Thanks for all you help

Answer:What do you mean by "importing sound"?

And in case you mean "recording sound and put it in a WAVE file", then what OS are you using? And which compiler?

breaking string into substring

Filed under: C Program — Tags: — admin @ 7:00 am

breaking string into substring


Answer:hi there

hi any one can tell me how could i break a string into substrings of variable length.

example:

string=30x 3X 21x

substring=30,x, ,3,x, ,21,x

thanx.


Answer:Well, you have three different kinds of characters:

¤Numbers (0,1,2…9)

¤Variables (Letters) (a,b,c…z)

¤Operators ( ,-,*,/)

1)

Start from the beginning of the string, if it is a number or letter store it then go to 2). If its an operator, store it and goto 3).

2)

Search the rest of the string. If the first character is the same as you found in 1), store it and repeat from 2). If it’s another kind of character, go to 3).

3)

Group the things you’ve stored in 1) and 2) into a string, then save it. Repeat from 1) with the rest of the string.

Repeat these steps until the string is empty.


Answer:Hi Sadat,

I currently am not having time to give u the entire program but here is the broad logic 4 it… An algorithmic approach to the solution already offered…

1. Read a character from the input string

2. if it is a numeric then go to step 3 else go to step 5

3. push it onto a stack (array of characters)

4. go to step 1

5. if stack is not empty then go to step 6 else go to step 8

6. convert the array of chars (string) to Int and store in the main stack (of strings- the final version of what u want)

7. go to step 1

8. if the read char is a symbol ( ,- etc) then go to step 9 else go to step 11

9. push it onto the final stack (strings stack)

10. go to step 1

11. if the read char is a char go to step 12 else go to step 14

12. push it onto the stack (strings) (assuming that only one character appears in between, else follow logic of steps 2,3,4)

13. go to step 1

14. (means end of string) TERMINATE process.

I am sure u can modify and refine the code for optimization. But thats ur job.

Warm Regards,

random number generation

Filed under: C Program — Tags: — admin @ 6:00 am

random number generation


Answer:Greetings,

I have been working on ways to create massive amounts of random numbers from 0 to 7. I have been going nuts with rand(). I want to create a program that will print out sets of 8 random numbers (from 0 – 7) until I tell it to stop. Like well over a billion times. I have studied rand() and srand() and tried many things but the same pattern of 8 numbers keep coming up. Even when I quit the app and restart it, it still has the same pattern of same numbers. A simple example:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

int main()

{

int x,y;

srand(time(NULL));

for(y=0;y<=100;y );

{

for(x=0;x<=7;x )

{

printf("%d ",rand()%8);

}

printf("\n");

}

}

Result:

1 6 7 4 5 2 3 0

7 4 5 2 3 0 1 6

5 2 3 0 1 6 7 4, etc

its the same pattern

even when I restart the app it is the same numbers with the same patterns

Im going nuts with this. I even entered random numbers for srand instead of time(NULL) and that did no good. I feel like I am missing something very simple. Can anyone point out what I am doing wrong? I have tried deleting the app and rebuilding. No good. I even rewrote my own rand() and srand() fucntions based on the ASNI C version. No good. Any advice?


Answer:This is probally a compiler issue. What compiler/os are you using? I have MSVC 6, Borland C Builder 5.0, Borland comand line compiler, and the new G and using that code produces no pattern. Also id suggest searching the board for random number generation since this has been talking about a kazillion times.

how to deactivate TSR ,how could we restore partition table

Filed under: C Program — Tags: , — admin @ 5:00 am

how to deactivate TSR ,how could we restore partition table


Answer:hi there

i am working on boot sector viruses and antiviruses and making an TSR antivirus using C.

but i have a problem

i can easily make my antivirus reside but how to deactivate it from memory????

one more question..

if a virus destroyes/overwrites/appends/copy anywhere the partition table,how could i restore it back.

thanks.


Answer:Umm

Answer:Hi

Not to sure if you can restore a partition table once it is removed, but check out microsofts web site.

They should have something there, I found the asm to remove any partition there.

And To All Those Opposed, Mmm Well


Answer:Hi there,

I havent worked with removing the TSR’s from memory but for the other part… You have the partition table located on the disk in some bytes (I would refer my book and get back on it) and what u do is, create a backup copy of those bytes in a file or something. When you need to restore ur partition table, simply re-dump those bytes into their original location.

I hope this would solve the second part of ur problem.

A possibility for the first part of the problem,….

First you reset the Interrupt so that it points to the default interrupt handler (removing ur functions address there) and then use a function like free or something to remove ur program from memory.

Best Regards

pls help!!!

Filed under: C Program — Tags: — admin @ 4:00 am

pls help!!!


Answer:how can i use an integer value for more than 32700???

Answer:unsigned int = 64000 (2^16)

long int = 3600000000 (2^32)

(with DOS int’s. Windows int’s has twice the size of DOS int’s)


Answer:Or in case of really huge numbers, design your own datastructure and operations. See also other threads on this topic on this board.

Embedded C

Filed under: C Program — Tags: — admin @ 3:00 am

Embedded C


Answer:Sorry to ask a really dumb question. I see lots of job adverts for embedded C programmers, what exactly is embedded C?

Thanks in advance!


Answer:Embedded C is what you program embedded systems with if you are going to use C. Simple as that. Not PC programming!

Answer:I don’t know if there really is Embedded C, but a lot of embedded systems are being programmed in C. Embedded software is software that is embedded in electronics. For example the software in mobile phones, cars, TV’s etc. As Garfield said, it is not the software that you’ll find on your PC.

But the software is usually written and build on a PC, using a cross-compiler, which generates binaries for the target device. Also the debugging tools run on PC. But the final product, the embedded software, runs in the device.


Answer:Many thanks for your help Garfield and Shiro. I kinda thought it would be something like that, but wanted to make sure. Thanks again!

I’m stuck with function, help plz

Filed under: C Program — Tags: , — admin @ 2:00 am

I’m stuck with function, help plz


Answer:Hi. Below is my program. I had to do one question with functions in my program, however, when i typed it out, i checked for errors but there were none. But only 3 warning messages, it says

‘possible use of ‘x’, ‘y’, and ‘z’ before definition in function main’

Ok, then, so i ignored that, hoping it would work anyways, the program runs, and when i type in my first integer and hit [enter] key, it gives me a critical error, something saying bout general protection processor fault (something like that). Could anyone help me out here, just by pointing out my mistakes in my program below, and give suggestions what i can do to fix it. Thx!

#include<stdio.h>

int add(int, int);

int subtract(int, int);

int multiply(int, int);

int divide(int, int);

float result = 0;

main()

{

int x, y;

char z;

printf("Please enter first integer: ");

scanf("%d", x);

printf("Now enter another integer: ");

scanf("%d", y);

printf("Now which operation would you like to perform with two integers?\n");

printf("Press ‘a’ for addition\nPress ’s’ for substraction");

printf("Press ‘m’ for multiplication\nPress ‘d’ for division");

scanf("%c", z);

switch (z){

case ‘a’: case ‘A’:

add(x, y);

printf("Addition: %d %d = %f.2", x, y, add(x, y));

break;

case ’s’: case ‘S’:

subtract(x , y);

printf("Subtraction: %d %d = %.2f", x, y, subtract(x, y));

break;

case ‘m’: case ‘M’:

multiply(x, y);

printf("Multiplication: %d %d = %.2f", x, y, multiply(x, y));

break;

case ‘d’: case ‘D’:

divide(x, y);

printf("Division: %d %d = %.2f", x, y, divide(x, y));

break;

default:

printf("I’m sorry, the key you typed in was not in operation menu.\n Please try again!");

}

return 0;

}

int add( int a, int b){

result = a b;

return result;

}

int subtract(int a, int b){

result = a – b;

return result;

}

int multiply(int a, int b){

result = a * b;

return result;

}

int divide(int a, int b){

result = a / b;

return result;

}


Answer:scanf takes a pointer as its second parameter…

like:

scanf("%d", &x);


Answer:oops

Answer:oops, i forgot that, damn, how can i make a silly mistake like that, hehe. Anywayz, got ur email right away, fixed that problem with scanf, now when i run the prog., i enter two integers, but unable to enter the last one, z. It immediately gives me the answer of default case. *sigh*, where am i wrong again??? am i supposed to use char for z??? i tried already with int z, i was able to input z, but gives me not found (used default case)

Answer:That’s a common problem with scanf – it’s leaving a newline inthe buffer – it’s been covered a lot on the boards…

Answer:oh man

Answer:*sigh*, so………….there is absolutely no way we can use scanf with characters, cant we? why is that? how come scanf does not allow this? Is there another possible way we can use besides scanf? (i only learned scanf to input, so i dont know whether there are other ways u can input, apart from declaring variables)

Answer:You don’t understand – the reason it’s messing up on the char input is because there’s still newlines in the buffer from the integer input before. It’s got nothing to do with you inputting a char.

Answer:The spaces take care of the newline buffer problem. Try fgets instead….

[edit]due to fgets solution below[/edit]


Answer: Code:
#include <stdio.h>
#define MAXLINE 1024

int add(int, int);
int subtract(int, int);
int multiply(int, int);
int divide(int, int);

float result = 0.0;

int add (int a, int b) {
result = a b;
return result;
}

int subtract (int a, int b) {
result = a - b;
return result;
}

int multiply (int a, int b) {
result = a * b;
return result;
}

int divide (int a, int b) {
result = a / b;
return result;
}

int main() {

int x, y;
char z[4]; //holds an integer up to 3 digits big.

printf("Please enter first integer: ");
fgets(z, MAXLINE, stdin);
x = atoi(z); //converts string to int.

printf("Now enter another integer: ");
fgets(z, MAXLINE, stdin);
y = atoi(z); //converts string to int.

printf("\nNow which operation would you like to perform with two integers?\n");
printf("Press 'a' for addition\nPress 's' for substraction\n");
printf("Press 'm' for multiplication\nPress 'd' for division\n");
printf("> ");
fgets(z, MAXLINE, stdin);

switch (z[0]) {
case 'a': case 'A':
add(x, y);
printf("Addition: %d %d = %.2f\n", x, y, result);
break;
case 's': case 'S':
subtract(x, y);
printf("Subtraction: %d - %d = %.2f\n", x, y, result);
break;
case 'm': case 'M':
multiply(x, y);
printf("Multiplication: %d * %d = %.2f\n", x, y, result);
break;
case 'd': case 'D':
divide(x, y);
printf("Division: %d / %d = %.2f\n", x, y, result);
break;
default:
printf("I'm sorry, the key you typed in was not in operation menu. Please try again!\n");
}

return 0;
}

Above I defined MAXLINE to be 1024 to be the max length of the buffer to be read from stdin. I also added char z[4] to be an array that can hold up to an integer 3 digits big (this includes the null terminator at the end of the string that is read in fgets).

rotate string

Filed under: C Program — Tags: — admin @ 1:00 am

rotate string


Answer:We want to read a string (max 20 characters) and display it turned around.

So ABCD becomes DCBA!

This should not be difficult, but we tried several things in C, but all didn’t work….!!

Please Help!!!


Answer:What’d you try?

Answer:We try to Convert a string:

From ABCD –> DCBA

We allready tried this:

#include "..\ownh.h"

#include "..\stdio.h"

int main (void)

{

/* Programm */

char mystring [10] ;

int waarde1 = 10;

char uitk [10];

float mystr [10];

int waarde2;

printf ("Fill in string value: ");

scanf ("%s",mystring);

printf ("String value is: %s\n",mystring);

while (waarde1 > 0)

{

printf ("Converted: %s\n",mystring waarde1);

waarde1 = waarde1-1;

}

printf ("%s",uitk);

pause ();

return 0;

}


Answer:…well gee, did you try the strrev function.

Answer: Code:
void stringturn(char *str)
{
unsigned int front,back;
char f,b;

back=strlen(str)-1; /* for the strlen() function you must include string.h */
for(front=0;front!=back;front , back--)
{
f=*(str front);
b=*(str back);

f^=b;
b^=f;
f^=b;
}
}

klausi


Answer:>...well gee, did you try the strrev function.

strrev isn't a standard function, he may not have it.

Code:

void stringturn(char *str)
{
unsigned int front,back;
char f,b;

back=strlen(str)-1; /* for the strlen() function you must include string.h */
for(front=0;front!=back;front , back--)
{
f=*(str front);
b=*(str back);

f^=b;
b^=f;
f^=b;
}
}

Oh yuck, not only does this not work, that XOR trick is really very nasty and should be avoided. Try something along these lines instead:
Code:

/* Pseudocode */
static void revstr ( char *a )
{
char b[BUFSIZ] = {0};
int s = 0, e = strlen ( a ) - 1;
while ( e >= 0 )
b[s ] = a[e--];
strcpy ( a, b );
}

-Prelude


Answer:How do I have to use the strrev option???????

Answer:If you want to use the strrev function then you should add the #include <string.h> at the begging of your .c file. The use for the strrev is "strrev (string);".

Answer:Thank you, Prelude for correcting me, but why is my "XOR-trick" "nasty"?

I used it to save the memory for a temporary variable.

Maybe that works:
Code:

char *stringturn(char *str)
{
unsigned int front,back;

back=strlen(str)-1; /* for the strlen() function you must include string.h */
for(front=0;front<=back;front , back--)
{
*(str front)^=(str back);
*(str back)^=(str front);
*(str front)^=(str back);
}

return str;
}

klausi


Answer:Well, thanks for the help,

We will try it tomorrow in school...

We just started programming in C one week ago...

When we have new problems we'll post them :-)

-----

Workgroup CIT Aventus


Answer:> When we have new problems we'll post them :-)

NO! Didn't you read.... oh of course you didn't. Silly me. Don't just post your problem, unless you've made an effort on your own, and post your try (IE: code) with your question.

If you get errors that you're working on, post the exact error. We are not the homework committee.

Quzah.

need to see if C program is already running in UNIX

Filed under: C Program — Tags: — admin @ 12:00 am

need to see if C program is already running in UNIX


Answer:My C program in UNIX can be triggered multiple times, but I want only the first one to run completely, while others coming out seeing that already an instance is running. Please help me to achieve this.

I was trying with getenv() and putenv(), but i am not having my variables in UNIX.

Thanks,


Answer:A simple way to do this would be to have your application look for a particular file in the /tmp directory. If it exists, exit. If it doesn’t, create it and continue on. The application must remove the temporary file before completing.

Answer:I just wrote a function to do this.

I used popen("ps -A", "r")

then read each line and used strstr to search for the command name.

Input for the function is the command name,

Output is the number of instances of the executable

I also wrote another function to get the command name based on a pid. So my call looks like:

if(exeRunning(exeName(getpid())) > 1) exit(0);

October 17, 2010

External error

Filed under: C Program — Tags: admin @ 11:00 pm

External error2!!!! HELP


Answer:Hi, I am new here. I am a 16 year old high school student. I typed this code for a windows skeleton and i have these 2 errors. IBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main

Debug/MyWin.exe : fatal error LNK1120: 1 unresolved externals

Error executing link.exe.

these errors come up after i execute my code. not after i compile it. these errors have come up on other codes too. this is my code:

#include <windows.h>

LRESULT CALLBACK WindowFunc(HWND, UINT, WPARAM, LPARAM);

char szWinName[] = "MyWin";

int WINAPI WinMain(HINSTANCE hThisInst, HINSTANCE hPrevInst,

LPSTR lpszArgs, int nWinMode)

{

HWND hwnd;

MSG msg;

WNDCLASSEX wcl;

wcl.cbSize = sizeof(WNDCLASSEX);

wcl.hInstance = hThisInst;

wcl.lpszClassName = szWinName;

wcl.lpfnWndProc = WindowFunc;

wcl.style = 0;

wcl.hIcon = LoadIcon(NULL, IDI_APPLICATION);

wcl.hIconSm = NULL;

wcl.hCursor = LoadCursor(NULL, IDC_ARROW);

wcl.lpszMenuName = NULL;

wcl.cbClsExtra = 0;

wcl.cbWndExtra = 0;

wcl.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);

if(!RegisterClassEx(&wcl)) return 0;

hwnd = CreateWindow(

szWinName,

"Windows 2000 Skeleton",

WS_OVERLAPPEDWINDOW,

CW_USEDEFAULT,

CW_USEDEFAULT,

CW_USEDEFAULT,

CW_USEDEFAULT,

NULL,

NULL,

hThisInst,

NULL

);

ShowWindow(hwnd, nWinMode);

UpdateWindow(hwnd);

while(GetMessage(&msg, NULL, 0, 0))

{

TranslateMessage(&msg);

DispatchMessage(&msg);

}

return msg.wParam;

}

LRESULT CALLBACK WindowFunc(HWND hwnd, UINT message,

WPARAM wParam, LPARAM lParam)

{

switch(message) {

case WM_DESTROY:

PostQuitMessage(0);

break;

default:

return DefWindowProc(hwnd, message, wParam, lParam);

}

return 0;

}

please help me out.

Thanks,

Jeff


Answer:What compiler are you using? It looks like you may have told your compiler you are building a console application in which case, the compiler will expect you to have coded a main function. The WinMain function is used for a Win32 application, the type of program you indicated you wish to create.

Answer:>error LNK2001: unresolved external symbol _main

This looks like an MSVC error. Most likely you are trying to compile a Win32 application in a console project, create a new Win32 application and then paste your code into that and recompile, it should remove that particular error.

-Prelude


Answer:I tried to create a win32 application and it said i couldn’t exacute it. why?

Answer:external help2!!!

Answer:i tried to create a win32 application and it wouldn’t let me exacute it. why

hangman need help with strings and pointers

Filed under: C Program — Tags: — admin @ 10:00 pm

hangman need help with strings and pointers


Answer:I need some help with my code as I’m not very familiar with strings and pointers. I need to have 6 functions in my code. So far I have only written 3. I now need a function to

a) Check if the guessed letter is in the word

b) Compare the word after every guess with the inputted word.

The problem is I must use pointers to search the string and compare the strings

/* Program that uses pointers and functions to create a simple 2 player version of hangman. Player 1 enters a 9 letter word, which has to be guessed by player 2. The 9 letter word entered by player 1 is to be displayed initially using 9 asterisks(*). As a correct letter is guessed, it replaces the asterisk at its proper location in the word. 3 wrong guesses and player two loses. If player 2 completes the word with less than 3 wrong guesses, s/he wins. The user is given the choice of quitting or playing again after every go. */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAXSIZE 9

void intro( );

void get_data (char *data);

char get_letter( );

void check_letter(char *data, char c, int * mistakes);

void output();

void main( )

{

char word[MAXSIZE], guess;

int miss = 0;

intro ( ) ;

get_data (data);

system("CLS");

while (miss < 3)

{

guess = get_letter();

check_letter(data, guess, &miss);

}

return 0;

}

/* FUNCTIONS*/

void intro()

{

printf(" ********************************************\n");

printf("Hangman \n");

printf(" ********************************************\n\n") ;

printf("Welcome to my game. Try to guess the word in the fewest possible goes. 3 wrong letter guesses and you lose! \n\n");

}

void get_data (char *data)

{

printf("Player 1, input 9 letter word for the other player to guess>");

scanf(“%c”, data)

while(data!=MAXSIZE)

{

printf(“ Error, invalid input. Enter a 9 letter word only\n”);

scanf(“%c”, data)

}

return data;

}

char get_letter( )

{

char c;

printf(“*********\n”);

printf(“Guess a Letter>\n”);

while ( getchar() != ‘\n’ );

scanf ( "%c", &c );

return c;

}

void check_letter(char word[MAXSIZE], char c, int *mistakes)

{

int i = 0, m = 0, n = 0;

do

{

if (word[i] != c)

{

printf("*");

m = 1;

}

else

{

printf("%c", c);

n = 1;

}

i = 1;

}while(i <= strlen(word));

*mistakes = m;

printf("You uncovered %d letters\n\n", n);


Answer:Well, for checking if the guessed letter is in the word, you should use the strchr function. The following code example is taken directly out of the MSDN Library and illustrates the use of this function:

Code:

Example

/* STRCHR.C: This program illustrates searching for a character
* with strchr (search forward) or strrchr (search backward).
*/

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

int ch = 'r';

char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] = " 1 2 3 4 5";
char fmt2[] = "12345678901234567890123456789012345678901234567890";

void main( void )
{
char *pdest;
int result;

printf( "String to be searched: \n\t\t%s\n", string );
printf( "\t\t%s\n\t\t%s\n\n", fmt1, fmt2 );
printf( "Search char:\t%c\n", ch );

/* Search forward. */
pdest = strchr( string, ch );
result = pdest - string 1;
if( pdest != NULL )
printf( "Result:\tfirst %c found at position %d\n\n",
ch, result );
else
printf( "Result:\t%c not found\n" );

/* Search backward. */
pdest = strrchr( string, ch );
result = pdest - string 1;
if( pdest != NULL )
printf( "Result:\tlast %c found at position %d\n\n", ch, result );
else
printf( "Result:\t%c not found\n" );
}

Output

String to be searched:
The quick brown dog jumps over the lazy fox
1 2 3 4 5
12345678901234567890123456789012345678901234567890

Search char: r
Result: first r found at position 12

Result: last r found at position 30

As you can see, it uses pointers so this should be acceptable for your use.


Answer:Re: hangman need help with strings and pointers

Answer:.

Integrals In C

Filed under: C Program — Tags: — admin @ 9:00 pm

Integrals In C


Answer:This is posted more for discussion than anything else.

Anyone who’s taken calculus know’s what an integral is. They’re the area under a curve governed by a function f(x) from a to b. What I’m wondering is, how does one program integrals in C/C ? Being that a computer can’t antidifferentiate like a human can, how would you tackle the problem?

What I’m thinking right now is it would be easy to simply use a Rhemann sum, and apply Simpson’s rule…. But then we run into the issue of approximations…

Any thoughts people?


Answer:As far as my memory goes, I used the Simpsons 1/3rd rule and solved it also using Newton-Ralphson method and Gauss formulas… I remeber using a limit variable for the number of iterations.

Answer:>But then we run into the issue of approximations…

That’s right. Remember that differentiation and integration are continuus operations, you work with infinite small elements. Since the computer can’t work with the term infinite, you’ll always have approximations. A computer simply can’t work with infinite small numbers or calclulate integrals or even series which run from for example zero to infinity. So numerical methods are always approximations of the continuus reality. There are many methods to compute integrals, you’ll find a lot with Google when searching for "numerical methods" and especially integrating.

system command

Filed under: C Program — Tags: — admin @ 8:00 pm

system command


Answer:hi,

Following code is not working.Help me

#include<stdio.h>

#include<dir.h>

void main()

{

system("myprogram.exe");

}

Please tell me that how system command command work.

Donot use link to tutorial of this site.It is not working.

thanks


Answer:If ur OS is Windows then forget abt it. It never worked for me either.

Answer:I’m not sure if you are getting a compile time or runtime error, but I believe system() is part of stdlib.h. Try including that.

If that does not solve your problem, please give a description of the error you are receiving.


Answer:Re: system command

Answer: Quote:
Originally posted by vk
system("myprogram.exe");

Also, your current working directory might not be what you think it is. Consider using the full path to ‘myprogram.exe’, instead of assuming it will be found.


Answer:Or have the executable file in the directory of the other program.

Answer:Try omitting the .exe off of the end.

Quzah.


Answer:>>Try omitting the .exe off of the end.

That wont do it. How about Try; "Giving some useful information such as what isnt working… Some errors maybe? Some symptoms? Throw us a bone!"


Answer:The problem is that you are just saying run this program when the current working directory is somewhere else.

Do this:
Code:

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

int main()
{
system("c:\\system\\program.exe");
return0;
}

That should work


Answer:And don't put in stdio.h because you do not need it...

!!!!!ANSI!!!!!!

Code:

#include <stdlib>
using namespace std; // or using std::system

int main()
{
system ("cls");
system ("pause");
system ("ping http://www.yahoo.com");
system ("yourfile.exe");
system ("pause");
system ("cls");
return 0;
}


Answer: Quote:
Originally posted by Betazep
And don't put in stdio.h because you do not need it...

!!!!!ANSI!!!!!!

Code:

#include <stdlib>
using namespace std; // or using std::system

int main()
{
system ("cls");
system ("pause");
system ("ping http://www.yahoo.com");
system ("yourfile.exe");
system ("pause");
system ("cls");
return 0;
}

Go back to the C board. We don't use name spaces or "<stdlib>" here.

Quzah.


Answer:LOL...

Sorry about that... followed it in from a link.

Do you use system? I thought that was a C standard function?????


Answer:http://www.dinkumware.com/htm_cpl/stdlib.html

Guess it is... so woops!!!


Answer:Many functions that are standard to C are also in C . Just like the syntax is the same. Basicly C is an extension of C, and as such, it has many similar functions and behaviour.

Quzah.


Answer:OIC

Can any one help?(about string)

Filed under: C Program — Tags: — admin @ 7:00 pm

Can any one help?(about string)


Answer:I’ve sth want to ask.Here is a part of my school project:

My testing value in variable Name is "Chan Tai Man"
Code:

void userData(char Name[20],char ID[10])
{
printf("Please enter your apply name : ");
fgets(Name,20,stdin);
//puts(Name);<----It can Output normally when in function as Chan Tai Man
printf("Please enter your ID card number : ");
GetIDCardNo(ID);

return;
}

After I get the Name in function 'userDate' and call another function "CreateAccount(uName,uID,index,Name,ID);"

The output inside this function is 000n Tai Man

After output this,the program hanged.And the error dialog appear

Expreession: str != NULL

I use VC


Answer:>Expression: str != NULL

This is an assertion failure, it means that a pointer you passed to a function was NULL, which shouldn't happen.

>I use VC

VC has a very nice debugging tool that you can use to step through your code and look at the values that are being shifted around. From there you should be able to see the problem easily.

-Prelude


Answer:Hmm, strange. I can't see any obvious errors, there.

Anyway, get a new compiler! VC SUCKSSSSSSSSS!


Answer:> Anyway, get a new compiler! VC SUCKSSSSSSSSS!

Another linux zelot. You have obviously never used MSVC . It's IDE is supurb. If you've ever created classes with it, or hell, if you've ever been typing any standard function names, it's invaluable. I mean really, how handy is it to have a "tool tip" display of the parameters for the function as you're filling them in? Pretty f-ing handy.

Quzah.

Adding largest floating point nos

Filed under: C Program — Tags: — admin @ 6:00 pm

Adding largest floating point nos


Answer:Hi

Can any one tell me how can i add largest floating point nos in machine the result may largest no as possible in my machine

thanks in advance

Dhiraj


Answer:In order to use very huge floating point numbers or floating point numbers with a large number of digits after the comma you need to design your own datastructure and operations that will work on it.

If you do a search on this board, you will find some other threads about this.


Answer:floating nos addition

Answer:Hi can u give me one example

Answer:There are many ways to do this. One way is to use linked lists, where each node contains a digit.

Code:

typedef struct _digit_s digit_s;
struct _digit_s
{
char digit;
digit_s *next_digit;
};

You could define a special character to represent the comma.

Code:

#define COMMA -1

Then you could do things just the same way you would do it on paper. Take care of the comma-position and the carry.

A different approach is using strings to store a number.


Answer:Download a package called NTL and link in into your program. It has a class for large float operations with arbitrary precision.

Second time I have recommended this in ten minutes.

timer tick algorithms

Filed under: C Program — Tags: — admin @ 5:00 pm

timer tick algorithms


Answer:Can any body provide me with an algorithm which can convert timer ticks to absolute callender date and time. and from absolute date and time to timer ticks.

the PCs use these algorithms. Solutions in any programming languages are wellcommed.

Thankyou

mohsin
mohsinzb@hotmail.com


Answer:>Can any body provide me with an algorithm which can convert

>timer ticks to absolute callender date and time. and from

>absolute date and time to timer ticks.

I don’t think it is possible to get calender date and time just from ticks. But if I remember well, it is possible to get the number of ticks since some date. And if you know the number of ticks, then you also need to know the number of ticks per second on your machine. And from then on, you can calculate back to date and time.

Assumption: start date is known / ticks per second is known

nr_of_ticks = get nr of ticks since date;

nr_of_seconds = nr_of_ticks / ticks per second;

nr_of_minutes = nr_of_seconds / 60;

etc.

>Solutions in any programming languages are wellcommed.

Algorithms are language independent.

PCI ISA bus Interface

Filed under: C Program — Tags: — admin @ 4:00 pm

PCI ISA bus Interface


Answer:How to write interface routine for a PCI or ISA bus card. ?

Are there any instructions for that or interrupts ?

What if i want to get images from a vedio graber card which is a PCI or ISA bus card ?

Conway’s Life

Filed under: C Program — Tags: — admin @ 3:00 pm

Conway’s Life


Answer:If anyone can help me by pointing me to a site that has a copy of a Conway’s Life program written in plain C language i would be most grateful.

Cheers


Answer:Did you try the Google search?

Alphabetical sort using STRCMP()

Filed under: C Program — Tags: — admin @ 2:00 pm

Alphabetical sort using STRCMP()


Answer:Hello, I’m a very novice programmer who needs help with writing a function. I am trying to write a program that reads in names in the format LASTNAME,FIRSTNAME. These names are entered into a two dimensional array of size [5][45]. A pointer array (*ar[5]) points to the orginal list of names entered. My question is how to write a function to sort these names in alphabetic (starting with the A’s names), given the above information. Any help or hints would be greatly appreciated. Thank you.

Answer:qsort is your friend.

Quzah.


Answer:ouch…but thanks

Answer:Thanks for the reply,

But, as a part of my assignment, Im not allowed to use qsort, I must write out a function that swaps names using strcmp, using variables such as temp to swap them with. Thanks for the help though, any additional help would be appreciated.

Array Data Structures

Filed under: C Program — Tags: — admin @ 1:00 pm

Array Data Structures


Answer:I have an array data structure struct book_type {

char title [30];

float price;

char authorName[30];

};

In the main program, I am trying to define an array of structures of the book_type (maximum 100 books) and pass the array of structures in the function, having the following prototype:

int readData( struct book_type [ ], int );

I have been working on this for the past day and a half and can not figure it out … i really need help on this one

ThanX


Answer:How do you pass the array to the function?

I think it should be done in a way like:

struct book_type book_types [ARRAY_SIZE];

readData (&book_types[0], data);


Answer: Quote:

I think it should be done in a way like:

struct book_type book_types [ARRAY_SIZE];

readData (&book_types[0], data);

No. Try this:

readData( book_types, myValue );

If you’re passing an array, you don’t need to bother specifying the address of its first element. Just use the array name.

If you’re passing a pointer to the array, that’s different. But if you’re just passing an array, just use its name.

Quzah.

strcmp clarification

Filed under: C Program — Tags: — admin @ 12:00 pm

strcmp clarification


Answer:Ola!

if I use the function

int my_strcmp(char * s1, char * s2)

{

/* S1 = Abba S2 = Ball*/

return strcmp(s1,s2);

}

What will the function return? Will it be a ve integer or negative? (Basically I’m asking how and what does strcmp return when you know the strings aren’t equal?)

Thanks for your help!


Answer:strcmp(s1, s2)

returns 0 if they are equal. returns 1 if s1 is greater than s2 and returns -1 if s1 is less than s2.


Answer:>Ola!

Word!

Since A<B, it should return a negative.

need graphics.h explaining.

Filed under: C Program — Tags: — admin @ 11:00 am

need graphics.h explaining.


Answer:Please help, being a novice programmer I am interseted to see what I can do with graphics.h. Please help.

Answer:Read and find out!!!!!!!

Answer:Ok you want to learn what graphics.h can do right. So go to the include folder and read the Text and study the commands and funtions and statements and see and learn what they do. Thats what I do to learn on my own, i read the header files and it shows you how to use certain funtions which is included in the header file.

Answer:I haven’t got graphics.h. Found it on the net, downloaded it and tried it. But it comes up with linking errors to termios.h, vga.h and vgamouse.h which i couldn’t find one of them on the net.

why?


Answer:Graphics.h has a collection of all the functions you need for writing a program involving graphics. One simple method is (if ur version of C supports) type graphics.h in the C-IDE and then click on CTRL F1 and it will show you a list of all the functions available in Graphics.h

Most of them need the support of a set of files from the Borland Graphics Interface (popularly called the BGI files). APart from these, they also need the graphics.OBJ file and some library files to work correctly. A good Installer of C would give all that you need. If u need one (a C compiler, older version) mail me and I’d be glad to. (BTW, I use TURBO C for DOS).

Regards,

Sriharsha.


Answer:I have devC 4 and it doesn’t have graphics stuff by default. Any ideas?

thnx


Answer:Me too I use it

Answer:I use Dev-C 4 for my codes and its great. Ok Listen BGI is very slow in graphics so Im saying to you forget graphics.h and move on to Allegro. Allegro is a game Library which can be used on Dev-C . just go to www.bloodshed.com and go to the extra add-ons and stuff and you will see Allegro for Dev-C 4.Because i have been using Turbo C 3 for DOS. And to use Graphics it was a hassel to learn and it was quit slow when its compiling. So what im saying to you is forget graphics.h and that BGI crap and move on to Allegro which is easier and much better.

Answer:OK thnx

But why do people still use grahics?


Answer:??????????????

Answer: Quote:

But why do people still use grahics?

People use graphics to make the game look more acceptable, you wouldnt want to play a game made out of ASCII now would you . So we use graphics i know i would. But for me Im done with 2D graphics and Im doing 3D graphics in a API called OpenGL . So all im saying to you is use Allegro for now because people have made pretty nice games with it.


Answer:nonono

i was actually asking about why do people still use Borland’s graphics.h libraries…..

thnx


Answer:You have to start somewhere. You can’t go direct on the OpenGL programming.

Answer:Thats not true…..

Answer:Its not true at all because i just went straight to OpenGL and im quit good in using it too

Answer:can u answer my lil qs pls thnx a lot

Answer:What was it?

Answer: Quote:
Originally posted by Nutshell
can u answer my lil qs pls thnx a lot

What was the question any way?


Answer:Re: What was it?

Answer: Quote:
Originally posted by opengl15

What was the question any way?

Too lazy to scroll up?

Well, the graphcs.h DOESN’T have the functions and stuff, only definitions. You also need the OBJ or LIB files.


Answer:Forget graphics.h

Answer:Just forget graphics.h because its too much to handle so do like i said and learn Allegro or something similar.

I’ve ran into a problem

Filed under: C Program — Tags: — admin @ 10:00 am

I’ve ran into a problem


Answer:Ok firstly, here is the assignment again, once again I’m not asking for an answer or any code, just what I’m dong wrong, hints, etc.

**************************************************

You are to write a program that evaluates simple arithmetic expressions which are composed by positive numbers (real or integers) and the four basic arithmetic operators: , -, * and /. The program will have to adhere to the following rules:

The expressions will be evaluated left to right (all operators will have the same precedence).

Blank spaces are ignored.

The expression is terminated by the end of the line, at which point you will display the answer.

The prompt is indicated with >.

You have to guard against illegal characters entered.

The program can be terminated only by pressing <CTRL-C>.

Ex:

> 2 3 * 4/6

3.333333

> 2/4 3

3.500000

> 2!/4 3

*** Illegal character !

>

Notes and Hints:

Since you want to loop indefinitely (until you enter <CTRL-C>), you have to set up an infinite loop:

do

{

/* Body of loop */

} while( 1 );

To test for end-of-line, you have to verify if the character read is equal to ‘\n’.

If you’ve encountered an error, before redisplaying the prompt, you need to clean the input line. This can be accomplished with the following code:

while( (c = getchar()) != ‘\n’ ) ;

You want to do this ONLY IF THERE WAS AN ILLEGAL CHARACTER

**************************************************

And now here is my code thus far:

**************************************************

/* This programevaluates simple arithmetic expressions which

are composed by positive numbers (real or integers) and

the four basic arithmetic operators: , -, * and /. */

#include <stdio.h>

int main()

{

float Answer, integer1;

char c;

printf("Please Enter the Mathematical Expression you want to

be evaluated:\n" );

scanf("%d", &Answer);

c = getchar();

do

{

switch ( c ) { /* switch nested in while */

case ‘ ‘: /* Read over white space */

scanf("%d",&integer1);

Answer = Answer;

break;

case ‘ ‘: /* Operand was */

scanf("%d",&integer1);

Answer = Answer integer1;

break;

case ‘-’: /* Operand was – */

scanf("%d",&integer1);

Answer = Answer – integer1;

break;

case ‘/’: /* Operand was */

scanf("%d",&integer1);

Answer = Answer / integer1;

break;

case ‘*’: /* Operand was */

scanf("%d",&integer1);

Answer = Answer * integer1;

break;

default: /* Operand was an invalid character */

while( (c = getchar()) != ‘\n’ );

printf("*** Illegal character!\n");

break;

} while(1);

printf("%d",Answer);

return 0;

}

*************************************************

Now the Major problem I’m getting: On compiling I’m getting an error that says "fatal error C1004: unexpected end of file found". I think its bcasue I have an indefinite loop, but according to the assingnment arent I supposed to have an indefinite loop?

Thanx in advance, I really really appreciate any help.


Answer: Quote:

"fatal error C1004: unexpected end of file found".

Your missing a ‘}’

Add a closing brace to your switch.

And use CODE TAGS makes it easier for us to read!!!!

How do you Load a Header file?

Filed under: C Program — Tags: — admin @ 9:00 am

How do you Load a Header file?


Answer:I want to load a header file I made…….but i dont know how to call it or interpret it in anyway. for example.

#include <windows.h> //windows main files

#include <gl/gl.h> //OpenGL main file

#include <gl/glu.h> //OpenGL library kit main files

#include "Loader.h" //Loads Bitmap Files

thats the problem I dont know how to call it so it can be used to load the Bitmap files and convert it to textures.


Answer:#include "Loader.h"

This statement is correct and any code that you wrote within that header file will be entered into your code during the preprocessor stage.

But, if that’s not what you mean, then please explain a little more clearly – I’m a tad confused.


Answer:……Not sure buddy

Answer:Like ok when you create a Header file and you want it to be compiled at a certain Line of the codes. for example.

01 printf(" Hellow world ");

05 ……right here you want to caLL the header file

10getchar();

So do you get what Im saying now


Answer: Quote:

05 ……right here you want to caLL the header file

You can’t call the header file, you include it.

If you mean call a function thats defined in your header file then you can call that function wherever.
Code:

#include "Loader.h"

int main( void )
{
// do stuff

Load_Bitmap(); // function defined in Loader.h

// do more stuff

return 0;
}


Answer:I'm still lost. Ugh.

Let's say your header file has this inside of it.

myHeader.h

#define maxline 1024

#define minline 10

myProg1.c

#include "myHeader.h"

... code ...

myProg.c is now (after the include):

#define maxline 1024

#define minline 10

... code ...

All that the include statement does is text insertion. If you want a certain function to be called at some arbitrary place in your code then write a seperate file (myOtherFile.c) with all of your functions and include it.

#include "myOtherFile.c"

Header file generally contain only constants, ifdef statments, etc..


Answer:I see what you mean

Answer:Oh I understand now, your saying I can call a funtion thats in the Loader.h file. At any time I want to in the code.

Ok so now its making sense to me thanks man.


Answer:another one

Answer:you must compile your functions into object file, then put them into library, then make a header file that is function declarations

then you can say include <bitmap.h> assuming you save your

objects and header file with the standard c headers altogether

Don’t know why this is happening

Filed under: C Program — Tags: — admin @ 8:00 am

Don’t know why this is happening


Answer:I’m just in the beginning stages of my code and already I’m in trouble.

The part that I’m working on is supposed to read a map into a 2d array, and I wanted to print out the array to see if I got the whole thing.

However, when I print it out, I get everything except for the half of the last line.

Here is my code so far:

#include <stdio.h>

#define MAXROW 50

#define MAXCOL 100

main ()

{

int Row_Num, Col_Num;

char Map[MAXROW][MAXCOL];

char Moves[50];

int ctr_Row, ctr_Col;

scanf ("%d %d", &Row_Num, &Col_Num);

if ((Row_Num<=MAXROW)&&(Col_Num<=MAXCOL))

{

printf ("%d %d\n", Row_Num, Col_Num);

for (ctr_Row=0;ctr_Row<Row_Num;ctr_Row )

for (ctr_Col=0;ctr_Col<Col_Num;ctr_Col )

scanf ("%c", &Map[ctr_Row][ctr_Col]);

for (ctr_Row=0;ctr_Row<Row_Num;ctr_Row )

for (ctr_Col=0;ctr_Col<Col_Num;ctr_Col )

printf ("%c", Map[ctr_Row][ctr_Col]);

printf ("\n");

printf ("%d %d", ctr_Row, ctr_Col);

}

return 0;

}

and when I run the prog, the counters all come out correct, so what gives? Any help is greatly appreciated.

Thanks

Doug


Answer:oh, and sorry about the formatting, I thought the indentations would come out.

Doug


Answer: Code:
#include <stdio.h> 

#define MAXROW 50
#define MAXCOL 100

main ()
{
int Row_Num, Col_Num;
char Map[MAXROW][MAXCOL];
char Moves[50];
int ctr_Row, ctr_Col;

scanf ("%d %d", &Row_Num, &Col_Num);
if ((Row_Num<=MAXROW)&&(Col_Num<=MAXCOL))
{
printf ("%d %d\n", Row_Num, Col_Num);
for (ctr_Row=0;ctr_Row<Row_Num;ctr_Row )
for (ctr_Col=0;ctr_Col<Col_Num;ctr_Col )
scanf ("%c", &Map[ctr_Row][ctr_Col]);
for (ctr_Row=0;ctr_Row<Row_Num;ctr_Row )
for (ctr_Col=0;ctr_Col<Col_Num;ctr_Col )
printf ("%c", Map[ctr_Row][ctr_Col]);
printf ("\n");
printf ("%d %d", ctr_Row, ctr_Col);
}

return 0;
}


Answer:all the characters I entered in printed out, the very first scan which reads the array dimension to use, is that meant to be inclusive, ie I put in "2 3" and entered 3 characters where as I would assume it should be 6 characters. If this is the problem you mean, then in the for statements that read:

Code:

for (ctr_Row=0;ctr_Row<Row_Num;ctr_Row  )
for (ctr_Col=0;ctr_Col<Col_Num;ctr_Col )

change it to

Code:

for (ctr_Row=0;ctr_Row<=Row_Num;ctr_Row  )
for (ctr_Col=0;ctr_Col<=Col_Num;ctr_Col )

Maintaining queues

Filed under: C Program — Tags: — admin @ 7:00 am

Maintaining queues


Answer:I have tried to run a simple program that allows a user to add self referencing data stuctures into a queue and then delete them from the queue.

Whenever I try to compile it in Visual C i get the following error:

error C2440: ‘=’ : cannot convert from ‘void *’ to ’struct queueNode *’

I took it straight from a book "C: How to program" by Deitel & Deitel.

I don’t know how to correct the problem, does anyone?

If so please let me know because it’s doing my brain in!

If you manage to compile it, could you please let me know what compiler you are using.

I’d really appreciate any suggestions.

Cheers!

Source code for queue.cpp:

#include <stdio.h>

#include <stdlib.h>

struct queueNode {

char data;

struct queueNode *nextPtr;

};

typedef struct queueNode QUEUENODE;

typedef QUEUENODE *QUEUENODEPTR;

void printQueue(QUEUENODEPTR);

int isEmpty(QUEUENODEPTR);

char dequeue(QUEUENODEPTR *, QUEUENODEPTR *);

void enqueue(QUEUENODEPTR *, QUEUENODEPTR *, char);

void instructions(void);

main()

{

QUEUENODEPTR headPtr = NULL, tailPtr = NULL;

int choice;

char item;

instructions();

printf("? ");

scanf("%d", &choice);

while (choice != 3){

switch(choice) {

case 1:

printf("Enter a character: ");

scanf("\n%c", &item);

enqueue(&headPtr, &tailPtr, item);

printQueue(headPtr);

break;

case 2:

if (!isEmpty(headPtr)){

item = dequeue(&headPtr, &tailPtr);

printf("%c has been dequeued.\n", item);

}

printQueue(headPtr);

break;

default:

printf("Invalid choice.\n\n");

instructions();

break;

}

printf("? ");

scanf("%d", &choice);

}

printf("End of run.\n");

return 0;

}

void instructions(void)

{

printf("\nEnter your choice:\n"

" 1 to add an item to the queue\n"

" 2 to remove an item from the queue\n"

" 3 to end\n");

}

void enqueue(QUEUENODEPTR *headPtr, QUEUENODEPTR *tailPtr, char value)

{

QUEUENODEPTR newPtr;

newPtr = malloc(sizeof(QUEUENODE));

if (newPtr != NULL) {

newPtr->data = value;

newPtr->nextPtr = NULL;

if (isEmpty(*headPtr))

*headPtr = newPtr;

else

(*tailPtr)->nextPtr = newPtr;

*tailPtr = newPtr;

}

else

printf("%c not inserted. No memory available\n", value);

}

char dequeue(QUEUENODEPTR *headPtr, QUEUENODEPTR *tailPtr)

{

char value;

QUEUENODEPTR tempPtr;

value = (*headPtr)->data;

tempPtr = *headPtr;

*headPtr = (*headPtr)->nextPtr;

if (*headPtr == NULL)

*tailPtr =NULL;

free(tempPtr);

return value;

}

int isEmpty(QUEUENODEPTR headPtr)

{

return headPtr == NULL;

}

void printQueue(QUEUENODEPTR currentPtr)

{

if (currentPtr == NULL)

printf("Queue is empty.\n\n");

else{

printf("The queue is:\n");

while(currentPtr != NULL) {

printf("%c –> ", currentPtr->data);

currentPtr = currentPtr->nextPtr;

}

printf("NULL\n");

}

}


Answer:I tried to compile it and had no problems and dont have vc installed so bit hard to figure out exact problem.

Answer: Quote:

newPtr = malloc(sizeof(QUEUENODE));

malloc returns a void *

some compiles have stricter type checking so you need to cast it

replace the above line with:

newPtr = (QUEUENODEPTR)malloc(sizeof(QUEUENODE));


Answer: Quote:

some compiles have stricter type checking so you need to cast it

Usually this happens if you’re using a C compiler. C requires type casting of void pointers.

Quzah.

speakers

Filed under: C Program — Tags: — admin @ 6:00 am

speakers


Answer:how can i send sound to the speakers not the internal speaker but to the output?

Answer:To my knowledge, you can’t do that with plain C. You would have to do something with DirectX (DirectSound) or some other library.

Answer:any popular or example libraries available? any free ones as well?

thnxq


Answer:Yeah, DirectX and then use DirectSound. It’s a free download at microsoft’s website.

Answer:On low level you would have to use the device driver of your soundcard. Easier is making use of the Win32 API functions. Take look at the MSDN library for an overview.

Answer:On very-low-level you would have to write a device driver for your soundcard and program the functions you need.

klausi


Answer:

Or on extreme-low level, you would have to create your own sound producing device and write software to control it.


Answer:Yes you can do this in C. However, for large buffer sizes you will need to make use of either XMS or EMS depending on whether you are in protected mode or not.

go to www.creative.com and click on the developers section. Then click on legacy sound programming and download the documentation for programming the SoundBlaster series of cards.

Note that this is only for DOS.


Answer:Bubba, would this be done in good ol’ assembly?

Answer:Well….yeah it can be.

But I have coded a full sound system in C. Waiting to port to DJGPP. Current problem is the size of the DMA buffer and getting the linear address of the buffer, not the logical one that the CPU translates to the linear.


Answer:Bubba, can you explain DMA for me?

Answer:DMA is a nifty way to transfer data to and from memory transparent of the CPU. In other words, the CPU does not even know about the transfer which makes it very fast and also frees the CPU up to continue its pipeline and do what it does best -> run instructions.

However, there are some limitations to DMA. First any buffer that is to be used by the DMAC cannot cross a physical 64K boundary, and second, the DMA cannot transfer more than 64Kb of data at one time. Thanks to the DMA hard drives can shoot data to memory very fast and sound cards and other devices can too. In my sound programming, I allocate a DMA buffer of 256 bytes, but program the sound card for half of that transfer. At the 128 byte mark, a hardware interrupt is generated on the sound card’s IRQ channel. I patch this vector, along with programming the PIC and some other things, and when the interrupt happens, I copy the next 128 byte chunk of data into the section that just played. If you always copy data into the buffer that just played, you can produce clickless sound output.

There are several modes for DMA transfer. Some popular ones are auto-initialized transfer and single cycle transfer. Auto-initialized is nice because you only program the DMAC chip once for the transfer length and the address of the buffer. It will increment that DMA channel’s count register until it reaches the size of the transfer. After that, it wraps back around to 0 and keeps transferring data. As the programmer, you just have to place new data into the buffer and you will be able to transfer large amounts of data with one program of the DMAC. You just alter the contents of the buffer.

With single-cycle DMA, the DMA will transfer the data in the buffer until the length is reached at which time it stops. On sound cards, this will produce a noticeable click or pop in the sound if you forget to shut off the speaker prior to reaching the end of the transfer. Also, there will be a slight delay in the buffer throughput since you must reprogram the DMAC for the next transfer.

With newer DMA chips there are also burst modes and high speed DMA transfer modes. Hard drives and other speed critical devices use theses modes. You can also use these modes for sound transfers and SB cards do support these modes, but I’ve gotten excellent quality w/o using these modes.

But as you can see, DMA is very fast and very handy. Now you can see why sound can be played at the same time a million other things are happening. The DMAC chip is executing the loop and the transfer, not the CPU. Those bytes never go to the CPU, just to the DMA and then to memory. The only time the CPU is used is when a hardware interrupt is encountered and you load new data into the DMA buffer, or reprogram the DMA for another transfer – depending on the mode you are using. As I said I’ve achieved clickless sound output with just a 256 byte buffer. My sound system will play and mix in real-time an unlimited number of samples, but does start to suffer some distortion when over 10 sounds are being played at once.

For more information check out this link and click on the link to the 8237A DMAC data sheet.

http://support.intel.com/support/con…heral/spec.htm


Answer:Wow! That’s a lot of information. You gave me a good idea of what it is and then I’ll check out that link. Thanks, Bubba!

recursive matrix multiplication

Filed under: C Program — Tags: — admin @ 5:00 am

recursive matrix multiplication


Answer:I’ve got my matrix’s built and ready to use. Iteratively, matrix multiplication is a snap (3 "for" loops) but am having a hard time getting the idea of it being done recursively. These matrix’s are always the size of 2(to the exponent k).. eg 2,4,8,16,32…

ANY help will be much appreciated!

* quick question *

Filed under: C Program — Tags: — admin @ 4:00 am

* quick question *


Answer:mmmm….I have a real quick question I hope someone can answer within an hour and a half….heh….here’s the thing……

We need to create a way to put our code into "silent mode"….if the user passes a "q" to the program through the command line, then none of the printf’s need to be shown….only the scanf’s……it’s supposed to show nothing except when they choose to "PRINT" the records…..so I figured the easy way to do it would be like this:

Code:

int silent=0;

if (silent=1)
{
printf("a bunch of junk");
}

scanf("%c",&character);

something of the nature....put a check to see if it has been flagged as silent...problem is I can't get my char *argv working...at the very beginning of the program i'm trying something like:

Code:

if (char *argv[1]=='q')
{
silent = 1;
}

but that's not setting it equal to one...or something isn't going right....can someone tell me how to make this successfully set to 1 if the user passes a 'q'? thanks.


Answer: Quote:

if (char *argv[1]=='q')

the above line is comparing 'q' to an address. Remember the char *argv[] is an array is char pointers.

Try this:

if(argv[1][0] == 'q')


Answer:that code works fine when i pass a q.....but if i don't pass anything the code flips out and shut down....suggestions??

Answer: Quote:

that code works fine when i pass a q.....but if i don't pass anything the code flips out and shut down....suggestions??

if (char *argv[1]=='q')

1) How about you check argc before using argv?

2) Why the hell do you have 'char*' in there??

if( argc > 1 && *argv[1] == 'q' )

Quzah.

help on code

Filed under: C Program — Tags: — admin @ 3:00 am

help on code


Answer:I was wondering if you’s could help me out with this problem. I want to display the following numbers in this format

0:0

1:0

2:0

3:0

4:0

and so on, but they come out on the screen like this 01234:0:0:0:0:0

any ideas???heres my code, thanks

#include <stdio.h>

#include <conio.h>

#define MAX 5

int array[MAX];

main()

{

int i, y;

for(i=0; i<MAX; i )

{

printf("%d", i);

}

for(y=10; y < 15; y )

printf(":%d", array[i y]);

getch();

}


Answer:Your printing out all of your 1st numbers in each pair all at once…

Answer:for (i=0;i ;i<whatever_number)

printf("%i : 0\n",i);

doesn’t that do it?


Answer:sorry I mean..

for (i=0;i<whatever_number;i )

printf("%i : 0\n",i);


Answer:also

Answer:yeah, the above code will work fine, thanks, but i would like to use 2 for loops for this operation.

Answer:Well, then you’re going to have to have to one loop embedded in the other or it wouldn’t work (aka your attempt)…

Answer:have it

Answer:yeah, ive got it now, thanks !

Code to find the day type of day in the year?

Filed under: C Program — Tags: — admin @ 2:00 am

Code to find the day type of day in the year?


Answer:I’m looking for code that can help me determine which day of the week it is, when the intput is just DD/MM/YYYY.

(where the D’s are days, the M’s is month and Y’s is year)

If anyone can help me out, that’d be great!


Answer:You need a know day. ie 01/Jan/2002 == TUE

Then find the difference in days to the known.

Divide by 7 using the % operator.

Add the return to the known to find the day of the week.

need to have an array of the number of days in a month

iMonthArray[12]={31,28,31,…….(note the first has to be the KNOWN month and loop Dec->Jan)

and one for the day of the week

sDay[7][64]={"Tuesday","Wednesday",….(note the first has to be the KNOWN day.)

ie 28 Feb 2002

iDiffYears=0

iDiffMonth=1

iDiffDay=27
Code:

for(i=0;i<iDiffMonth;i  )
{
iDayDiff =iMonthArray[i];
}
iDay=iDayDiff%7;
sprintf(sDay,"Date is a %s",sDay[iDay]);

some macros could help

if you store the data as a long int

ie 01/Jan/2002 = 01012002

ie 28/Feb/2002 = 28022002
Code:

#define		GETDAY(lDate)		(lDate / 1000000)
#define GETMONTH(lDate) ((lDate / 10000) % 100)
#define GETYEAR(lDate) (lDate % 10000)

Then look for leap years and you are home


Answer:Use The code Given Below

main()

{

int x,y,z;

long int n,a,b,c;

clrscr();

cout<<"Enter Any Date in (dd/mm/yyyy) format "<<endl;

cin>>x;cin>>y;cin>>z;

if(y<=2)

{

a=z-1;

b=y 13;

}

else

{

a=z;

b=y 1;

}

n=((1461*a)/4) ((153*b)/5) x;

c=((n-621049)%7);

switch(c)

{

case 0 : cout<<"The Day Is Sunday"<<endl;

break;

case 1 : cout<<"The Day Is Monday"<<endl;

break;

case 2 : cout<<"The Day Is Tuesday"<<endl;

break;

case 3 : cout<<"The Day Is Wednesday"<<endl;

break;

case 4 : cout<<"The Day Is Thursday"<<endl;

break;

case 5 : cout<<"The Day Is Friday"<<endl;

break;

case 6 : cout<<"The Day Is Saturday"<<endl;

break;

}

If You Dont Get It then mail me at
kathireshn2001@yahoo.co.in


Answer:I don't understand some of the constants.

Code:

n=((1461*a)/4) ((153*b)/5) x;
c=((n-621049)%7);

1461 = 4 * 365.25 (OK)

Why (153*b)/5 ? (average days per month?)

Where does 621049 come from? (621049/365.25 = some day in 300AD)

Have you taken into account the change to the Gregorian calendar?

C Hardware Interaction

Filed under: C Program — Tags: — admin @ 2:00 am

C Hardware Interaction


Answer:I am a novice in C and I have always been told about the proven potential of C in controlling hardware. But HOW?

Could anyone be please kind enough to inform me of any resources pertaining to C ’s hardware access abillity?

Thank you very much to all those who replied.


Answer:A possible direction

First of all there is a point to be considered …

COntrolling H/w through

a. DOS

b. Windows

So, select ur OS.

If it is DOS, then you again have 2-3 ways…

1. Direct memory manipulations using pointers.

2. Using Interrupt Services

3. Using DOS Routines (inc. BIOS routines)

If you would like to use Windows then…

1. Take the help of windows API (if ur appl. needs interaction with windows components)

2. Go ahead just like dos programming style (if ur application does not need to interact with other apps and also only if u use Windows 9x. Win NT, 2000 etc are not supported in this mode).

Best Regards,

Sriharsha.

Functions problem. *Need Help*

Filed under: C Program — Tags: — admin @ 1:00 am

Functions problem. *Need Help*


Answer:ok this program has been driving me nutz. I have it working perfectly just useing arrays without functions. But when i go cut n paiste it into functions and try to get it working right it throws up at me. can anyone help mw out? getting lots of really odd errors.

/* The program determines the gross pay and ouputs the following

format:

————————————————————–

Clock# Wage Hours OT Gross

————————————————————–

098401 10.60 51.0 11.0 598.90

526488 9.75 42.5 2.5 426.56

765349 10.50 37.0 0.0 388.50

034645 12.25 45.0 5.0 581.88

127615 8.35 0.0 0.0 0.00*/

#include <stdio.h>

#define ARRAY_SIZE 5

void Get_Hours(long int[], float[],int);

void Calculate_Gross_Pay(float[], float[], float[], float[], int);

void Calculate_Overtime_Pay();

void Print_Header();

void Print_Results();

/************************************************** ************************/

/* Function Print_Header – */

/* */

/* Purpose: This function will print the header for the output */

/* and send it to the screen. */

/* */

/* Parameters: none */

/* */

/* Returns: void */

/************************************************** ************************/

void Print_Header (void)

{

printf ("————————————————————–\n");

printf ("Clock# Wage Hours OT Gross \n");

printf ("————————————————————–\n");

}

/************************************************** ************************/

/* Function Print_Results */

/* */

/* Purpose: This function will print the results of our program */

/* to the screen following the Print_header function */

/* */

/* Parameters: */

/* */

/* Returns: void */

/************************************************** ************************/

void Print_Results (long int clock_number[], float wages_array[], float hours_array[], float othours_array[], float gross_array[])

{

int i;

for( i = 0; i < 5; i)

{

printf ("i %5.2f %5.1f %5.1f %5.2f\n", clock_number[i], wages_array[i], hours_array[i], othours_array[i], gross_array[i]);

}

}

/************************************************** ************************/

/* Function Get_Hours */

/* */

/* Purpose: This function will */

/* */

/* */

/* */

/* Parameters: */

/* */

/* */

/* */

/* Returns: */

/************************************************** ************************/

void Get_Hours (long int clock_number[],

float hours_array[])

{

int i;

for( i = 0; i < 5; i)

{

printf ("Enter hours for %i", clock_number[i]);

scanf ("&hours_array[i]);

}

}

/************************************************** ************************/

/* Function Calculate_Gross_Pay */

/* */

/* Purpose: This function will calculate the gross pay for five */

/* employees. It will add to the gross pay any overtime */

/* pay if necessary. */

/* */

/* Parameters: wages_array – array of wage rates for each employee */

/* hours_array – array of # of hours each employee worked */

/* otpay_array – array of overtime pay for each employee */

/* gross_array – an array of the calculated gross pay for */

/* each employee. */

/* emp_count – the number of total employees */

/* */

/* Returns: Nothing since the gross_pay array is passed by reference */

/************************************************** ************************/

void Calculate_Gross_Pay (float wages_array[], float hours_array[], float otpay_array[],

float gross_array[], int emp_count)

{

int i;

for (i = 0; i <= 40)

/* calculate gross pay */

gross_array[i] = 40 * wages_array[i] otpay_array[i];

else

gross_array[i] = wages_array[i] * hours_array[i];

}

}

/************************************************** ************************/

/* Function Calculate_Overtime_Pay */

/* */

/* Purpose: This function will calculate the gross pay for five */

/* employees. It will add to the gross pay any overtime */

/* pay if necessary. */

/* */

/* Parameters: wage – rate of pay for the employee */

/* hours – # of hours the employee worked */

/* ot_pay – overtime pay for the employee */

/* */

/* Returns: gross pay (including any overtime pay) for the employee */

/************************************************** ************************/

void Calculate_Overtime_Pay ()

{

if (othours_array[i] > 40)

return (othours_array[i] – 40);

else /* no overtime was worked */

return (othours_array[i]=0.0);

}

void main ()

/* Create and fill Clock# Array*/

int clock_number[ARRAY_SIZE];

clock_number[0] =98401;

clock_number[1] =526488;

clock_number[2] =765349;

clock_number[3] =34645;

clock_number[4] =127615;

/*Create and fill Wages Array*/

float wages_array[ARRAY_SIZE];

wages_array[0] =10.6f;

wages_array[1] =9.75;

wages_array[2] =10.5;

wages_array[3] =12.25;

wages_array[4] =8.35f;


Answer:right off hand, I don’t see a main () .

all functions need to be called from the main ()


Answer:found it

void main () {

/* Create and fill Clock# Array*/

int clock_number[ARRAY_SIZE];

clock_number[0] =98401;

clock_number[1] =526488;

clock_number[2] =765349;

clock_number[3] =34645;

clock_number[4] =127615;

/*Create and fill Wages Array*/

float wages_array[ARRAY_SIZE];

wages_array[0] =10.6f;

wages_array[1] =9.75;

wages_array[2] =10.5;

wages_array[3] =12.25;

wages_array[4] =8.35f;

Get_Hours (clock_number[], hours_array[]) ;

Calculate_Gross_Pay (wages_array[], hours_array[], otpay_array[], gross_array[], emp_count) ;

Calculate_Overtime_Pay () ; /* othours is not global and will need to be passed to the funtion. */

} /* end of main */


Answer:hmmm….

Answer:well i know that i didn’t put the calls for the functions in yet. But I am getting errors in the functions that i can see why.

example in my Get_hours function i get

C:\Documents and Settings\David Moore\Desktop\C Class\Homework 5b.cpp(92) : error C2001: newline in constant

which points to scanf ("&hours_array[i]);


Answer:Delete this thread please….

Answer:All set. Got most of it working. Thanks to all the 30 people who viewed this thread

Path problems

Filed under: C Program — Tags: — admin @ 12:00 am

Path problems


Answer:I’m in the middle of implementing ps, except I have a problem with the concatenation of some of my paths. It’s supposed to look like this

/proc/xxx/stat

Where xxx is the process id, instead I get this

/proc/xxx/xxx/stat

Code:

/*This program will scan through a directory
if it finds subdirectories within it, it will
check if the name of the directory is a digit
if it is it will return 1, otherwise a 0. Based
upon the return value, the program will print the
filename which was matched i.e. 1 was returned. */

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <regex.h>
#include <unistd.h>

/*prototypes*/
int matchDetails(char* filename,char* path);
void printDetails(char* filename,char* path);
char *get_regerror(int errcode,regex_t *compiled);

int main(void){
int result,count,index; /*Set Conditions*/
char path[] = "/proc"; /*Path to the proc directory*/
struct dirent **direntp; /*Directory entry pointer*/
struct stat sbuf; /*Holds information about files*/

if (stat(path,&sbuf) != -1){
if(S_ISDIR(sbuf.st_mode)){
count = scandir(path,&direntp,NULL,alphasort);
if(count){
char temp[FILENAME_MAX];
printf("PID\tTTY\t\tTIME\tCMD\n");
for(index=0; index<count; index){
strcpy(temp,path);
result = matchDetails(direntp[index]->d_name,temp);
if(result > 0) /*If directory name was matched*/
printDetails(direntp[index]->d_name,temp);
free(direntp[index]);
}
}else{
fprintf(stderr,"Can't open %s\n",path);
exit(EXIT_FAILURE);
}
}else
return;
}else{
fprintf(stderr,"Can't stat %s\n",path);
return;
}
return EXIT_SUCCESS;
}

/*Used to find process directories*/
int matchDetails(char* filename,char* path){
int status,regstat;
char *pattern = "[0-9] "; /*Match digits only*/
char *result;
struct stat sbuf;

/*Get the full pathname*/
strcat(path,"/");
strcat(path,filename);

/*Stat the full path name*/
if(stat(path,&sbuf) != -1){
if(S_ISDIR(sbuf.st_mode)){ /*If a directory*/
regex_t re;
if((regstat = regcomp(&re,pattern,REG_EXTENDED | REG_NOSUB)) != 0){
result = get_regerror(regstat,&re);
fprintf(stderr,"%s\n",result);
return(0);
}
if((status = regexec(&re,filename,(size_t) 0,NULL,0)) != 0)
return(0);
regfree(&re);
}else
return(0);
}else{
fprintf(stderr,"Can't stat %s\n",filename);
return(0);
}
return(1);

}

/*Print the process information*/
void printDetails(char* filename,char* path){
FILE *f_name;
int pid;

/*Format the path*/
strcat(path,"/");
strcat(path,filename);
strcat(path,"/");
strcat(path,"stat");

if((f_name = fopen(path,"r")) != NULL){
fscanf(f_name,"%d",pid);
printf("%d\n",pid);
fclose(f_name);
}else
fprintf(stderr,"Can't open %s\n",path);

}

/*Used to store regex errors*/
char *get_regerror(int errcode,regex_t *compiled){
size_t length = regerror(errcode,compiled,NULL,0);
char *buffer = malloc(length);
(void) regerror(errcode,compiled,buffer,length);
return buffer;
}

October 16, 2010

string array reversing…

Filed under: C Program — Tags: — admin @ 11:00 pm

string array reversing…


Answer:We allready posted a topic for turning around an String.

But we are no experts, so we don’t really understande the code that was posted….

We need a EASY programm for converting a string:

from (for example)

ABCD –> DCBA

We allready made this:

#include "..\ownh.h"

#include "..\stdio.h"

int main (void)

{

/* Input of String-array *

char mystring [21] ;

printf ("fill in a string: ");

scanf ("%s",mystring);

printf ("The string you entered is: %s\n",mystring);

/* Rotation of string */

while (waarde1 > 0)

{

printf ("Rotation: %s\n",mystring waarde1);

waarde1 = waarde1–;

}

printf ("%s",uitk);

pause ();

return 0;

}

Now we have the problem that we cant select 1 sign from the string, but only from a sign.

So we want to select each string value, and then paste them together in reverse angle….

Please help us….

No difficult C code (or the "strrev" command)… only this simple problem…


Answer: Code:
#include "..\ownh.h"
#include "..\stdio.h"

int main (void)
{
/* Input of String-array *
char mystring [21] ;
printf ("fill in a string: ");
scanf ("%s",mystring);
printf ("The string you entered is: %s\n",mystring);

/* Rotation of string */
while (waarde1 > 0)
{
printf ("Rotation: %s\n",mystring waarde1);

waarde1 = waarde1--;
}
printf ("%s",uitk);

pause ();
return 0;
}

waarde1 = waarde1--; is unnecessary, just having waarde1--; will do the same thing.

Not sure about your #includes, what kinda compiler you using and on what OS?

printf ("%s",uitk); is also not going to work, uitk is never defined ever. For that matter neither is waarde1.

What exactly is this rotation? Your trying to reverse a string right?

Heres an example of what I would do.

Code:

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

#define MAX 21

int main(void) {
char string[MAX];
int size;

printf("Give me a string foo: ");
scanf("%s", string);
printf("String entered is: %s\n", string);
size = strlen(string);

printf("Here is string in reverse: ");
while (size >= 0) {
printf("%c", string[size]);
size--;
}

return 0;
}


Answer:We programm in Windows 98, A windows Compiler (version 12.0)

linker version 6.0.

We use a "homemade programm" to link in Dos..

(Our teacher at school designed it..)

He also made the pause () command. So the Dos prompt doesnt close (first press a key...)

the programm you posted doesnt work, It goes through the compiler, but it the linker its stuck...

The Strlen command is wrong..

We dont know it anymore....


Answer:What error does the linker give? strlen works perfectly fine for me? Might have something to do with how you did your #includes before.

As for the pause thing, I use batch files to compile and execute my programs so I dont have to retype it everytime. In my batch file I include a pause so I dont have to put a pause in the program itself.


Answer:We made it....

Got a little help from our teacher....

Here is the code:

#include "..\ownh.h"

#include "..\stdio.h"

#define MAXCHAR 10

int main (void)

{

/* Programma */

char mystring [MAXCHAR];

int ii = 0; /* aantal tekens */

int aantal;

printf ("voer string-waarde in: \n");

scanf ("%s",mystring);

while (mystring[ii] != '') ii ;

while (ii>=0)

{

printf ("%c",mystring[ii-1]);

ii--;

}

printf ("\n");

pause ();

return 0;

}

Sorting an array alphabetically?

Filed under: C Program — Tags: — admin @ 10:00 pm

Sorting an array alphabetically?


Answer:I am using structures of arrays, and one of the arrays holds football teams. I want to organise the data alphabetically, and have it displayed. Can this be done?

Answer:Hmmm. So if I am correct you have a structure with arrays as members and one of the arrays contains the names of football teams. And you want to organise that array alphabetically. Yes, that is possible, you could sort the array and then print it out. You can use qsort, part of the standard library, to sort the array.

Windows from C?

Filed under: C Program — Tags: — admin @ 9:00 pm

Windows from C?


Answer:Is Windows OS really was developed using the C language ?

Are there any proofs of this ?

Thanks

A Curious Mind


Answer:I really don’t know how they can hard-code all these cool 3d windows using C.

Answer:Windows was written with a combination of C, C , VB for most of the "cool 3d windows", and Assembler.

-Prelude


Answer:If I am correct, the Windows API is written in C. So yes, it is possible to do that stuff in C.

Sorting aphabetically?

Filed under: C Program — Tags: — admin @ 8:00 pm

Sorting aphabetically?


Answer:I am trying to sort an array of structures alphabetically. Can this be done?

if yes, how? I can only find sorts that organise numerically. Any help would be appreciated.

Blue Bob


Answer:If you’re sorting characters or strings thats the same as sorting numbers, since they get converted to their ascii equivalents.

Answer:Yes, just read the string in each struct’s first character and compare. Simple as that…

Answer:Or …

Code:

int strcmp (const char *s1, const char *s2);

from string.h


Answer:Doesn't that function just tell if the strings are the same or not? Returning only a 0 or 1. Please correct me if I'm wrong...

Answer:Check your system's documentation on the qsort() library function. I believe that is what you are after.

Answer: Quote:
Originally posted by Garfield
Doesn't that function just tell if the strings are the same or not? Returning only a 0 or 1. Please correct me if I'm wrong...

if s1 is less that s2, strcmp will return a negative number. if they are equal, zero is returned. if s1 is greater than s2 strcmp will return a positive number.

Random File Issues

Filed under: C Program — Tags: — admin @ 7:00 pm

Random File Issues


Answer:Here is a struct I use to write to a random file:

————————————————————————

typedef struct {

int eqNo;

char eqName[20];

float price;

int stock;

int reorder;

} equipment;

————————————————————————

Here is the variable definition:

————————————————————————
equipment Equip = {0,"",0.0,0,0};

————————————————————————

I open the file like this:

————————————————————————
fPtr = fopen(filename, "r ");

————————————————————————

NOTE: filename is a string variable with the actual filename

This prints the data stored in this struct for individual records from the random file just fine:

————————————————————————
printf("1 – Item # : [%d]", Equip.eqNo);

printf("2 – Name : [%s]", Equip.eqName);

printf("3 – Price : [%.2f]", Equip.price);

printf("4 – In Stock : [%d]", Equip.stock);

printf("5 – Reorder : [%d]", Equip.reorder);

————————————————————————

But this, when reading from the random file, prints the first few records, and then gibberish…

————————————————————————
while(!feof(fPtr))

{

fread(&Equip, sizeof(equipment), 1, fPtr);

if (Equip.eqNo != 0)

{

printf("%-7d%-20s%-10.2f%-9d%-8d",Equip.eqNo,

Equip.eqName, Equip.price, Equip.stock, Equip.reorder);

}

}

————————————————————————

The above while loop code works for all of my other structures and random files EXCEPT the structure mentioned above.

So, what am I doing wrong with that loop? Is there something wrong with this loop or is there something wrong with the structure? If you need any more code to help your reasoning, just ask. Thanks in advance.


Answer:can u try this and see if it works:

Code:

fread(&Equip, sizeof(equipment), 1, fPtr);
while ( !feof ( fPtr ) ) {
if ( Equip.eqNo != 0 ) {
printf("%-7d%-20s%-10.2f%-9d%-8d",Equip.eqNo,
Equip.eqName, Equip.price, Equip.stock, Equip.reorder);
}
fread(&Equip, sizeof(equipment), 1, fPtr);
}


Answer:fseek seems to do a neat trick...

Answer:I see what you're saying, I haven't tried it yet but I'm going to in a short while. However, an interesting thing happened when I tried fseek inside the loop. Check this out...

-----------------------------------------------------------------------

x = 0;

while(!feof(fPtr))

{

fseek(fPtr, (x) * sizeof(equipment), SEEK_SET);

fread(&Equip, sizeof(equipment), 1, fPtr);

if (Equip.eqNo != 0)

{

printf("%-7d%-20s%-10.2f%-9d%-8d",Equip.eqNo, Equip.eqName, Equip.price, Equip.stock, Equip.reorder);

}

x ;

}

-----------------------------------------------------------------------

This solves the problem I was having earlier.

However I am having an interesting issue. Sometimes when I store data in this structure, the reorder field converts its int value to a long string of numbers. Usually data entered in the reorder field is like "5", "10", "20" or something like that. But when you print out the information, it is sometimes something like "187273726392".

Do you have any idea why this happens?


Answer:Your code produces the same output

Answer:When I tried your code, it produced the same output. It worked the first time. So I tried to input new data and it produced the same semi-gibberish output the second time around.

Don't worry about that, the fseek seems to work ok. What I'm now having trouble with is the reorder field of the structure. It keeps changing the integer value stored in it to some long string of numbers. I capture data in the field like this:

fflush(stdin);

scanf("%d", &Equip.reorder);

and like I had mentioned before, the data captured in this field is a small integer number like 5, 10, 15 or 20 etc. However, when you print out the records in the file, the reorder field for SOME of the records (not all) is a corrupted long string of integers. Any idea of why this happens?


Answer:You might try opening the file in binary mode, both when you write the file and read it.

fPtr = fopen(filename, "rb ");


Answer:Binary mode?

Answer:Not to seem stubborn, but why should binary mode make a difference when I've used the same code (read, writing & printing code) for several other structs and random files and never came across this issue?

Do you think it's because the last field is an int field?

sizeof

Filed under: C Program — Tags: — admin @ 6:00 pm

sizeof


Answer:Hi,

My question is

at what level is "sizeof" operator resolved?

to elaborate,

if I have sizeof(int), what decides the size of int? the CPU? if yes then would the sizeof(int) give the same value when executed in the same machine say once in linux and then in windows in a dual boot system?

if compiler decides it then can it be played around? (Just a figment of my imagination.)

thanks,

Anoop.


Answer:It’s definitely determined by the hardware thats for sure, and i also believed ( not 100% ) that it’s the CPU.

Not sure for your 2nd question.


Answer:The Instruction Set Architecture (ISA) decides it. These are the instructions that the CPU understands and are specific to the CPU.

Now it is possible to define diferent sizes, but then you also have to define the operations. An example of this was before a float was standardized, different implementations existed for it. These had to be defined, usually in assembly.

If you look in limits.h file, you should see a lot if conditional logic for defining the sizes of primatives based on the processor and/or ISA.


Answer:sizeof

Answer:Does that mean that every time the compiler encounters the sizeof operator, it has to switch to the kernel mode and interact with the machine. That would be too costly.

And since if limits.h defines the limit then that means we can manipulate it and make a program crash during runtime.

I could be terribly wrong in my assumptions so please excuse them. Its just that it has baffled me.

Thanks

Anoop.


Answer:When ever the sizeof operator is encountered it refers to the value defined in limits.h.

Now if you changed limits.h it could cause compile and runtime errors with the application, but would not affect the operating system. Basically, limits.h is one of those files that you should not edit.


Answer:so i guess basically u could have different values in limits.h in different systems.

Open Source and profit…

Filed under: C Program — Tags: — admin @ 5:00 pm

Open Source and profit…


Answer:I’ve spent 23 years (on and off) developing an action-planning-tool.

I’m learning C so I can design a prototype so it can be "protected" while I seek venture capital, etc.

My local-closest-to-guru-guy said I need to be aware of open source library use because if I include certain functions/libraries I would not be able to sell the code due to open source "copyright" or is that "left"?

I definitely want to sell the tool; I’ve worked hard on it, will soon work even harder and feel compensation is due…

Yet..

I’m not greedy…

I do want the tool to be widely used…

Maybe I’d be willing to make the damn thing OS…

As long as some aspect or service connected with it could generate income…

/*Quandry*/

Alex


Answer:You should read this.

Answer:Thanks, Deckard!!!

String Handling

Filed under: C Program — Tags: — admin @ 4:00 pm

String Handling


Answer:I’m learning C so I can write a prototype of an action-planning-tool.

I know I’ll need a massive thesaurus-module.

Anyone have leads?

Also, what’s the "best" source for string-handling (interactive) routines?

Alex

Port-Ability

Filed under: C Program — Tags: — admin @ 3:00 pm

Port-Ability


Answer:What’s the "best" "all-round" guide to portability concerns.

/*part 2*/

Is the "safest" C called "Clean" or ASCII or ISO or Standard or ???

Alex


Answer:The "safest" C is ANSI standard. You’re the first person I’ve ever heard call it "clean".

Answer:"Clean C"

Answer:I got the term from the book, C – A Software Engineering Approach by Peter A Darnell & Philip E. Margolis.

Alex

Why does an integer print like that?

Filed under: C Program — Tags: — admin @ 2:00 pm

Why does an integer print like that?


Answer:I have a structure defined as such:

typedef struct {

int eqNo;

char eqName[20];

float price;

int stock;

int reorder;

} equipment;

and I capture the data for each field like this:

fflush(stdin);

gets(Equip.eqName);

fflush(stdin);

scanf("%f", &Equip.price);

fflush(stdin);

scanf("%d", &Equip.stock);

fflush(stdin);

scanf("%d", &Equip.reorder);

However, when I print out this information, the last field, reorder, prints out a long string of integers instead of the value actually placed in it. This only happens for some of the records.

Has anyone ever experienced this issue? If so, could you kindly enlighten me please? Thanks.


Answer:Try this instead:

fflush(stdin);

gets(Equip.eqName);

fflush(stdin);

scanf(" %f", &Equip.price);

fflush(stdin);

scanf(" %d", &Equip.stock);

fflush(stdin);

scanf(" %d", &Equip.reorder);

Other than that; I’d have to think for awhile…


Answer:Don’t use gets, use fgets instead since you can limit how many characters get copied into your eqName buffer. This will eliminate the chance that some idiot types in a name longer that the space available and winds up overwriting some memory location some where.

As for your question, how are printing out the data. Show us that code as well since it could be a piece of the puzzle.


Answer:hk_mp5pdw – the printing source code :

x = 0;

while(!feof(fPtr))

{

fseek(fPtr, (x) * sizeof(equipment), SEEK_SET);

fread(&Equip, sizeof(equipment), 1, fPtr);

if (Equip.eqNo != 0){

printf("%-7d%-20s%-10.2f%-9d%-8d",Equip.eqNo,

Equip.eqName, Equip.price, Equip.stock, Equip.reorder);

}

x ;

}

Let me explain a few things here. The file is written using the following code:

fseek(fPtr, (Equip.eqNo – 1) * sizeof(equipment), SEEK_SET);

fwrite(&Equip, sizeof(equipment), 1, fPtr);

I have created no sophisticated hashing algorithm to determine a random position in the random file to store the actual data, so I simply used Equip.eqNo – 1 to do that.

The user enters a number for the eqNo field. (a simple int between 1-100, as the file can store a max of 100 records)

The reorder field is however, also an int. But what I notice is that for each subsequent record written, the reorder field for the previous record gets corrupted.

I hope this makes sense. Do you know what could be happening here?


Answer:>scanf("%d", &Equip.reorder);

I would add a printf() here to see if reorder got stored.

Also, did you open the file in binary mode when you wrote it and read it back?

fopen(filename,"wb");


Answer:It works at home!

Answer:The strangest thing, when I take the program home, it works beautifully. No idea why.

I’m running Win NT 4 on NTFS 4 at work.

At home I’m running Windows 2000 with FAT 32.

I wonder if that has anything to do with it.


Answer:that could well be the problem, The architecture of each system. You are using 32bit at home and possible 16bit at work.

to resolve the problem copy your file at home from binary to text file. Small self written program to do this. Reverse process at work so that the binary file created is in the correct architecture.

while(feof)

fread(your structure, binfp)

fprintf(textfp, your structure variables)

/* to write to text reverse to write binary*/

Large number library?

Filed under: C Program — Tags: — admin @ 1:00 pm

Large number library?


Answer:Well since my first question never got answered here I figure I’ll take one last shot at the forums… Anyone know of a header file or library that will give me functions to deal with numbers of unlimited size? (Add, sub, mul, div, etc…)

I’m working on my own; but hey; don’t re-invent the wheel right?


Answer:Please?!?! Someone!?!?

Answer:up^

Answer:easy

Answer:you have to use one dimension arrays to do that. then after you had taken the numbers from stdin you can make a function that will make add adn sub. for the time just repeat add many times.

Answer:Download a package called NTL. You can find it through any search engine. It has a Windows and Unix/Linux versions.

Better scanning method

Filed under: C Program — Tags: — admin @ 12:00 pm

Better scanning method


Answer:Say I had a file with the following values in it

100 200 300 400 500

Now I want to assign a to 100, b to 300 and c to 500. Am I correct in thinking that fscanf has to scan through each one like this?

fscanf(file,"%d %d %d %d %d",&a,&b,&c,&d,&e);

There has to be a better way of doing that,without having the needless variables!!!


Answer:If that works, why don’t you just use it? The whole idea of high level languages like C, is to not write code when someone else has done it for you.

Answer:Here’s the way:

Code:

# include <stdio.h>
# include <conio.h>

int main()
{
FILE *fin= NULL;
int Numbers = 0;

fin = fopen("numbers.txt", "rt");

while (fscanf(fin, "%d", &Numbers) != EOF)
{
printf("\nNumbers = %d", Numbers);
}
getch();
return 0;
}

Have phun!


Answer: Quote:
Originally posted by Sean
If that works, why don't you just use it? The whole idea of high level languages like C, is to not write code when someone else has done it for you.

...unless you can do it better, of course


Answer:What i'm basically trying to say is that I don't need 200 and 400 so why waste the space by declaring extra variables, especially when in some cases there can be 20 values in a file and I only want to use 4 of those values for the program. Thanks GaPe but there doesn't seem to be a conio.h in linux

Answer:The "conio.h" library is just for the "getch()" command and it is used to stop the program. In this case it is useless.

Answer:So does that answer my problem then, taking the conio and getch out of your method just make the program print all the numbers.

Answer:Yes.

Answer:you could try this:

Code:

fscanf(file,"%d %*d %d %*d %d", &a, &b, &c);

the * will cause the input field to be skipped and no assignment will be made.


Answer:This methode is inefficient. If you want to save your numbers than you should do this with an array of integers.

Answer: Quote:
Originally posted by GaPe
This methode is inefficient. If you want to save your numbers than you should do this with an array of integers.

his original question was this:

Quote:

Originally posted by pdstatha
Say I had a file with the following values in it

100 200 300 400 500

Now I want to assign a to 100, b to 300 and c to 500. Am I correct in thinking that fscanf has to scan through each one like this?

fscanf(file,"%d %d %d %d %d",&a,&b,&c,&d,&e);

There has to be a better way of doing that,without having the needless variables!!!

mine answers that. yours does not. whether your code is more efficient than what i gave him doesnt really matter in this case.


Answer:besides, what does yours really do? if he wanted to store the numbers in an array of int, he could do something like this:

Code:

#include <stdio.h>
#include <stdlib.h> //for strtol()
#include <string.h> //for strlen()
#include <ctype.h> //for isdigit()

int main(void)
{
char line[1024];
char *endp;
int iArray[100] = {NULL};
int i, j = 0;

FILE *fileptr;

if((fileptr = fopen("filename.txt", "r")) == NULL)
{
printf("Could not open file!\n");
return 0;
}

while(fgets(line, sizeof(line), fileptr))
{
line[strlen(line) - 1] = ''; //removes the '\n'

for(i = 0; i < strlen(line); i)
{
if(isdigit(line[i]))
{
iArray[j ] = strtol(&line[i], &endp, 10);
while(isdigit(line[i])) i;
}
}
}
for(i = 0; i < j; i)
printf("%d ", iArray[i]);

fclose(fileptr);
getchar(); //not needed if run from command prompt
return 0;
}

EDIT: bah, i should really compile these things first.

EDIT2: oops, didnt include 0 as a number that may show up in the file... not good... fixed now.


Answer:I was just showing him the way how to display the numbers. If you want to save them here's the way of doing it:

Code:

# include <stdio.h>
# include <conio.h>

int main()
{
FILE *fin= NULL;
int i = 0, Numbers = 0, IntArray[100];

fin = fopen("numbers.txt", "rt");

while (fscanf(fin, "%d", &Numbers) != EOF)
{
IntArray[i ] = Numbers;
}
getch();
return 0;
}

Have phun!


Answer:ok, thats pretty much the same thing i posted except i

i used fgets, strtol, and getchar instead of fscanf and getch.

you say you were showing him how to print out the numbers but his post wasnt asking for that. i still dont see how the efficiency of...

Code:

fscanf(file, "%d %*d %d %*d %d", &a, &b, &c);

really matters in this case. i just answered his question. he wasnt asking how to print the numbers out or save them to an array of int.


Answer: Quote:

you say you were showing him how to print out the numbers but his post wasnt asking for that.

I know that but I just want to show him how to read numbers from a file and I didn't want to give him a direct solution.

Quote:

i still dont see how the efficiency of...
Code:

fscanf(file, "%d %*d %d %*d %d", &a, &b, &c);

really matters in this case. i just answered his question

And what about if you have 1000 of numbers in your file. What will you do?? Write 1000 variables for each number or you will be smart and saved them into an array of integers?

Authoring issue

Filed under: C Program — Tags: — admin @ 11:00 am

Authoring issue


Answer:Who should have the recognition of creating and developing C language?

What specific language did he use and OS?

Thanks

curiouse mind


Answer:Dennis Ritchie and Brian Kernighan invented C, which was based, fittingly, off the language B. They wrote it to create Unix.

hardware interaction in c

Filed under: C Program — Tags: — admin @ 10:00 am

hardware interaction in c


Answer:hi there,

this is vineet.i am in MCA fourth sem.planning to submit "system manager for dos" as a minor project,which would provide a GUI for formatting(A drive),scanning and many other utilities.but i am facing a lot of problems.it would be really nice of u if u could help me with the following..

1–>how can i provide information about all the partition’s on the sytem i.e. it’s free and used space.

2–>How can i show exat RAM size used(it’s 192 in mine).

3–>it would be really nice of u if u could provide me information about media discreptor of floppy(1.44MB).

vineet..


Answer:At first you should write what compiler do you use and in which operating system are you writing your code.

Answer:>system manager for dos

I assume you’re using DOS. You could use the info in the BIOS.


Answer:How can i use the info in the BIOS? DOn’t u need assembly stuff do access the partition table and things like that?

Answer:> How can i use the info in the BIOS? DOn’t u need assembly stuff do access the partition table and things like that?

In the first case, No assembly is required to access partition table information and any of the Hardware resource information for that matter. C (I use Turbo C) provides u a rich set of functions to do the same for some and for the others u always have memory under ur spell, so get the values from various memory locations. U can also have information from CMOS using the system CMOS ports 70h & 71h.

For partition table…

The hard disk is partitioned using utilities like DOS’s FDISK. While partitioning the hard disk, FDISK stores the details like where one partition ends and the next begins, which is the bootable partition etc in the first physical sector (side 0, track 0 sector 1). It also stores a program called Master Boot Program in the PT (partition table). Thus a PT consists of a data part and the code part. This is how the PT is logically divided…

Code Part Data Data 55

(master boot program) data data AA

————– ———————– ———–

446 bytes 64 bytes 2 bytes

totally : 512 bytes

The data part begins at the 447th byte. the last 2 bytes in the PT are always 0×55, 0xAA. The data part is 64 bytes long and is further divided into 4 16-bit chunks. Each chunk consists of info abt a partition on the HDD. Hence there can be maximum four partitions on the HDD. (dont confuse with logical drives which can by any number). The break up for those 16-byte chunks are …

Byte Meaning

—– ———–

0 Boot Indicator. Contains 0×80 for active partition and 0

otherwise.Only 1 partition can be active at a time

1 Side where partition begins

2 Low-six bits are the sector where partition begins

Two-high bits are the two high bits of the track where

partition begins

3 Low order 8 bits of the track where partition begins

4 Partition type indicator. The following values may exist…

0 – Unused partition

1 – DOS partition using 12-bit FAT

2 – Unix Partition

4 – DOS partition using 16-bit FAT

5 – Extended partition

6 – Huge Partition

5 Side where partition ends

6 Low-six bits are the sector where partition ends

Two-high bits are the two high bits of the track where

partition ends

7 Low order 8 bits of the track where partition ends

8-11 Double word containing the number of sectors preceding

the partition. Low order word is stored first

12-15 Double word containing the number of sectors in

the partition. Low order word is stored first

So, with these details, go ahead and try a program off ur brains… But remember (There is no mention for 32-bit FAT or Linux native / swap partitions. So, this is a premitive stuff (not suited for the latest partitions), so just be careful)

Best regards,

Sriharsha.

*Note: Dont play with ur PT or else U have to reset the whole disk.


Answer:What are the functions that can access the partition table?

Answer:I never remember using any Off-the shelf functions. I always wrote it on my own.

I guess u can do it with the info i provided above.

Computer check

Filed under: C Program — Tags: — admin @ 9:00 am

Computer check


Answer:I am writting a 3D tic tac toe program, I was wondering if any one coudl help me figure out how I can make the computer recognize a line formation.

i.e. setting each box as an integer, how can teh computer see this to try and stop a line formation from teh user


Answer:Don’t know exactly what you mean. But you can store a 3D array in memory and use that to check lines.

Older Posts »

Powered by WordPress