Thursday, September 17, 2009

challenge of GetInt(char* str, int num)

void GetInt(char *str, int num){

int n=num;

int count=0;

while(n>0){

n/=10;

count++;

}

*(str+count)='\0';

for(;count>0;count--){

*(str+count-1)=num%10+'0';

num/=10;

}

}

Here is all my code for this challenge. It's different from the notes in class because we cannot use std library, so the first thing came to my mind was use a number plus '0', but at the very first, I need to know how long this number is. And I write while(n>0){ n/=10; count++; } . Then, I change the integer to string from very last to the beginning, so I use the for loop for(;count>0;count--){ *(str+count-1)=num%10+'0'; num/=10; } . Finally, I just want to end the string, and I got *(str+count)='\0'; in the middle. That's all my steps.

Review of C

1. First of all, we can use logical operator (&&) instead of some if statements. The structure of if statement is if( condition) { statement;}, if the condition is true, it will do the statement. But we can also do that by using && . Like condition && statement; , it's the same to if statement, if the condition is false, it will not look at it.
Here is the website links to example :
https://cs.senecac.on.ca/~fardad.soleimanloo/oop344/notes/02-Sep10/oplazy1.c

2. # include "file.h". It uses double quote, meaning the file is in the same directory. It will copy the date in the file.h to the current file, and be executed when the program starts. You can divide a program into two parts, and put each of them in a file. Then, write a program just contains two #include "filename" in it. You will get the same result.
Example :
https://cs.senecac.on.ca/~fardad.soleimanloo/oop344/notes/02-Sep10/whatever.what
https://cs.senecac.on.ca/~fardad.soleimanloo/oop344/notes/02-Sep10/foo.faa
https://cs.senecac.on.ca/~fardad.soleimanloo/oop344/notes/02-Sep10/include.c

3. #define a b. It's the same as replace. Simply, all the a will be replaced by b. So be careful with this, #define SUM b+c. When you see SUM*a in the program, it will just do b+c*a.
Example :
https://cs.senecac.on.ca/~fardad.soleimanloo/oop344/notes/02-Sep10/define.c