somjit{} 60 Junior Poster in Training Featured Poster

got it!!! yay! :D

entering condition: l=0,h=5,mid=2

left block:                                                      right block:
  partition(arr,0,2)  {takes 0,2 to next iteration, prints it}     partition(arr,3,5) {takes 3,5 to next iteration, prints it}

    L: partition(low=0,mid=1)   R:partition(mid+1=2,2)               L: partition(3,4)        R:partition(5,5)  

        {this goes on to          {this loop terminates              {this makes                  {terminates with printing 5,5}
        make further calls          by printing 2,2}                  another call
        affecting both L,R blocks}                                    affecting L,R blocks again}              
        .                             .                                     .               .   
        .                             .                                     .               .

        so on...

thus, each left and right block division also has an effect on the other block... resulting in the printing of the low=high terms.

i got it :)

thanks for pointing out the key @deceptikon :)

somjit{} 60 Junior Poster in Training Featured Poster

oh ..no...! i think im getting it....

somjit{} 60 Junior Poster in Training Featured Poster

When low and high are equal, the printf() still executes even though the contents of the if statement do not.

lets take : low = 0 , high = 1;

**low<high?** yes

    thus, mid =0 (  (0+1)/2  )
    partition(array, low=0, mid=0) called.. // this is for the recursive division of the left block of the array

        **low=0 and high=0 printed**
         going into if() block... 
                                      **low<high** ? ans: no... (low=high=0 here)
                                      no more partion() calls
                                      end of left block recusrcive division


also, when low = 0 , high = 1, mid=0; 
    partition(array, (mid+1=1), high=1) called      //this is for the recursive division of the right block of the array

         recusrsion is now called with low=1, high=1
            1,1 should be printed.... 

                going into if()...

                                    **low<high** ? ans: no... (low=1 high=1 here)

                                    no more partion() calls
                                    end of right block recusrcive division

this is how the flow of the code seems to me.. but i dont get how all those low=high cases gets printed... you said printf() still executes even when low<high doesnt hold... i can understand that part occuring once, for each of left and right block division... in the case when 0,0 and 1,1 gets printed. but after that, why didnt the whole iteration stop ?

somjit{} 60 Junior Poster in Training Featured Poster

but it's not. So regardless of the values of low and high, you're still printing output; the two are unrelated.

the printf() might not be inside if(), but if() states the condition when partition() will be called (recusrsively).. so doesnt that make the printf() dependent on if() ?

i know the solution might be pretty simple, but i cant seem to understand it.. :(

somjit{} 60 Junior Poster in Training Featured Poster

basically used to parse a text into smaller tokens, based on the delimiter u provide...
c89 standard strtok.. should give u an idea...

$ is the delimiter here, the function takes the address of the stringto parse, so NULL probably means your not passing any string to it.

and if ur interested, this place tells u something about the bad sides of strtok... u can take a look at it too.

somjit{} 60 Junior Poster in Training Featured Poster

the code works perfectly, just i got something i dont understand...

i'v been trying to get a hold of recursion and sorting for about 3-4 days now, im getting some of it, but still not happy enough..

i searched for some good code for binary search and merge sort on the net, found some, took the one i liked most, and have been editing it to my needs. it would have felt a lot better had i been able to write both on my own,
but....
i cant..... :(
(hence all the downloading, editing and testing and comparing ... :| )

well , i have two codes:

  1. the main binary search code
  2. the merge sort one, saved as a header file and called from binary search one...

works perfectly, even after all my edits... this is the output......

for_dani_merge1

here is the part of the code that generates it:

void partition(int arr[],int low,int high){

    int mid;
    static int count=0;
    printf("inside partition, for this step>> low : %3d    &   high : %3d  , step number: %d\n",low,high,count++);
    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         mergeSort(arr,low,mid,high);
    }

}

the array consists of random numbers (generated via srand(), and rand() inside a for() loop, thus saving me time), and this array is passed to the partition() function contained in my merge-sort header file. everythings fine, just one confusion regarding the output:

i dont understand why i get output for cases (step number: 3,4,5 and 8,9,10) when "low" …

somjit{} 60 Junior Poster in Training Featured Poster

i messed up there... perhaps posted on a hurry..

im going through everything again.. inlight of what u said.. hopefully wont mess up this time...

thank you so much for the detailed answers, learning alot.. :)

somjit{} 60 Junior Poster in Training Featured Poster
    char *s;
    foo(&s, 15);
    strcpy(s, "this is a test");

in these lines, s is transformed from a character to a character array that contains the string "this is a test" ... this is whats happening here right? and thus foo() allocates memory to s... im getting it...

This is more or less the same functionally as if you allocated the memory to s directly in main().

yup! got it.. i think...

as regards the c11 standard, can u givesome links? i follow that page (c89 one) completely, so i guess im missing a lot perhaps...

If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.

so a pointer declared as static will have the same effect when fed to a realloc() as in case of a malloc()...?
but what if the pointer was originally pointing to something else?? do we do a {free() + pointer=NULL} on it? is it a good way? or we reset it??

if reset; then is reset ==
1. keeping an original copy of the pointer,
2. assigning that original to the pointer at a later time

is this the default way to reset?

You'll notice that nowhere does it mention anything along the lines of behaving like free()

the idea i had was something like this:

free() makes a dangling pointer, that gives need to assign NULL to it... ? so the place it says

somjit{} 60 Junior Poster in Training Featured Poster

Don't do it because it's neat. Do it when it makes the code easier to read.

yes sir :)

somjit{} 60 Junior Poster in Training Featured Poster

the pointer you pass may be reset to point to memory allocated within getline()

im a bit unclear here...

1.memory allocated with getline() ??

  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, stdin);

malloc allocates memory to my_string[], according to user input (nbytes). hoe does getline allocate memory ?

also;

    free(my_string);
    my_string=NULL;

is this whats meant by pointer resetting?? i looked it up on the net, the code examples seemed huge.. lost patience :| they said something like "setting a pointer so that it points to 0" , so i assume this is what they mean?

As AD mentioned, if bigDaddy is already big enough then just read directly into it. The partial line stuff with fgets() is mostly for when you're building a string dynamically and don't know how long the line might be (or similar situations).

thankyou :) got it :)

edit:
this place says to store a backup copy of the pointer,

this place says this about realloc:

void * realloc ( void * ptr, size_t size );

size
New size for the memory block, in bytes.
If it is 0 and ptr points to an existing block of memory, the memory block pointed by ptr is deallocated and a NULL pointer is returned.

why do that to make a pointer null? if pointer is to be made null, free() + pointer=NULL …

somjit{} 60 Junior Poster in Training Featured Poster

printf(((result * result)== number)? "":" NOT");

thats a neat way to print ;) gonna do that myself when possible :)

somjit{} 60 Junior Poster in Training Featured Poster

and make another call to get the rest of the line

i want to append the next partial line to the partial line that was just read, what do i do then?

char buf[BUFSIZ];
while (fgets(buf, sizeof buf, stdin)) {
    fputs(buf, stdout);
    /* Did we read a partial line? */
    if (buf[strlen(buf) - 1] == '\n')
        break; /* No, all done */
    else
        strcat(bigDaddy,buf);
}

will this work?? i think it should work as long as bigDaddy is big enough :D

is there another more preffered way to this?

somjit{} 60 Junior Poster in Training Featured Poster

Which book

ANSI C @ dennis ritchie, pg 45 lower part

"the book"?

i think so ;) \m/

and well, i think im misinterpreting it ... coz i just ran the code, and it works too...

in case of integer, itsays to cast it into double, like

sqrt((double)int);

whats happening here ?

somjit{} 60 Junior Poster in Training Featured Poster

Which book is "the book"?

ANSI C @ dennis ritchie

and im probably misinterpreting it :(

somjit{} 60 Junior Poster in Training Featured Poster

result= sqrt (number);

doesn't sqrt() take argument of type "double" by default??

the book says sqrt() will return non sensical values if given argument of type int? but it seems to work.. so why say that in the book?

somjit{} 60 Junior Poster in Training Featured Poster

read here that fgets() is bad, although no explanation given... also i think the default getline() isnt in C , is it??

why is fgets() bad??

also, the page on getline says it takes in char** as the 1st input type... whats a '**'? why is it used?? i couldnt get an answer when i googled it... any help?? :(

somjit{} 60 Junior Poster in Training Featured Poster

We don't write code anymore

being marvin makes you so lazy! :D

We make you do it! ;-D

debugging surely makes you feel crazy?! :D (sometimes atleast..)

on a serious note...

thank you :) for helping meout with my crazy codes :)

somjit{} 60 Junior Poster in Training Featured Poster

this thread is solved! learned a lot .. thankyou @waltP and @deceptikon :)

kinda wish @ had the same effect like that on facebook ... maybe you guys can write a code for that too :D

somjit{} 60 Junior Poster in Training Featured Poster

ill settle with number 6.. :) will write something else some other day for characters.. :)

somjit{} 60 Junior Poster in Training Featured Poster

You've pretty much got it...

thanks to you guys:)

things running as they should... i havent yet checked the outputs with self calculation yet, but things look good:) atoi() doing whatit should.. i enter 65, and im getting both 'A' and 65 in the right places....
only one thing, because of atoi(), i have to enter 'A' as 65, else it wont work...

this is the char2shrt() block:

void char2shrt(void)
{
    char input[40];
    char  ip;
    short op;
    printf("enter input:\n");
    fgets(input,39,stdin);
    printf("\nyou entered: %s",input);
    ip=atoi(input);
    printf("\nYou entry after going through atoi(): %c",ip);
    op = ip;
    printf("\nthe output in type short is: %hd",op);
}

almost there i guess... :) just if you could tell me how to input 'A' and get an output for that (if thats possible, given the nature of the code) ,it would be great :)

feeling good :)
once again, thank you so much :)

somjit{} 60 Junior Poster in Training Featured Poster

so to think of it... each type translates the binary in its own way, and as long as the binary remains same, the output remains "understandably" different... just like 65 and 'A' are...

so if we apply this logic to the

ip=input[0]

problem....

back there, the issues were:

  1. only one digit was loading into the cases like char2shrt() int2shrt() and i wanted multiple inputs
  2. as a solution to this problem, came int stoi() and atoi() , but i had a doubt with the return types being always int

so if im getting it right, then although the return type is int in a function like char2shrt(), as long as the return value stays small, and within the limits of char (and thus short too) , the binary wont be messed up, and we can retrieve good data from int , pass it to char or short, and get an "understandably" different output.. just like 65 and 'A'....

right??

somjit{} 60 Junior Poster in Training Featured Poster

its like i thought it would be, the data remains same, only the output format is different

when 65 is loaded to both int and char, output on console shows 65 for int, and A for character...

as regards why...
i think its because integer displays the data stored in it, while char compares its data to ASCII, and displays the character that matches it (ie the data stored in it).

is it like that?? i havent looked it in the internet.. really, im just too excited about it to look anywhere, im just blurting out my thoughts via the keyboard into this page .... am i going the right way?

somjit{} 60 Junior Poster in Training Featured Poster

What you have is -123

+5= (0)0000101
+123= (0)1111011,
thus -123= ( (NOT)(+123) )+1= (1)0000100+1=(1)0000101 // two's compliment form

also, two's compliment@(+5)= (1)1111011 = -5, coz only then (+5)+(-5)=0
thus, (-5) != (1)0000101

i think im getting it now :) thanks for pointing it out :)

as regards

int a;
char b;
a = b;

lets see....

int = 4bytes, char=1byte...

so when we do

a = b;

the char byte gets copied into the lowest byte of int.

results: (what i can think of)
1. consedering both int and char were positive numerical values, i think no harm would be done... the first 3 bytes would be 0's anyways, however
2. if it was like char b='A', then value stored in b=65, (binary: 10000001), and when it gets copied into int a, although a will contain

(0--0)(0--0)(0--0)(10000001)

byte4|byte3|byte2|byte1= value of char

i dont think an integer can give 'A' output to the console... although data stored is the same...

did i make sense?

somjit{} 60 Junior Poster in Training Featured Poster

this video explained a lot...

somjit{} 60 Junior Poster in Training Featured Poster

Some things you need to figure out:

1) What happens when you pass a character variable to a function that wanted an integer?
2) What happens when you return an integer into a character variable?

Some things you need to figure out:

1) What happens when you pass a character variable to a function that wanted an integer?
2) What happens when you return an integer into a character variable?

from what i understand:

  1. char==1byte==8bits
    therefore, if i call 'ch' a char variable, and assign it value 5, then binary ways:

ch= 10000101 (signed negative char)

when i pass ch=5 into a variable of type int; the lower 3 bits , ie 101 gets bit-mapped into the lowest LSB's of 32bit int,
so its like: 1xxxxxxx-xxxxxxxx-xxxxxxxx-xxxxx101 (assuming a negative number)
what happens to the middle 'x' es area is mystery to me too :(
that's why i wanted to write this code to give me data to understand the theory behind it..

and yes...
whatever i wrote above can be absolutely wrong too :D

im looking it up now... lets see....

and now that you said it, i had a question too, what happens when the sign bit of char value -5 (ie binary: 10000101) goes into a higher byte format (a 2byte short lets suppose) ,then what happens to the msb 1 of 10000101 in 1xxxxxxx-10000101, does it stay 1? coz i assume then the value gets changed.... ?? …

somjit{} 60 Junior Poster in Training Featured Poster

i assume since i have varied kinds of input data types in different functions(int2shrt, char2shrt etc..), so i'll need to make an stoi() that return different types as well...
or will int stoi() suffice for all the cases ? in that case, i can also use atoi() directly too right?

You progressively get a digit, find it's numeric value (by subtracting the character '0'...

i can think of two cases:
1. its related to the ASCII value of the characters? '0' being some value x, and '1' has value (x+1)??
2. the other one being related to pointers, and array indexing starting with 0, but as ur doing (*s-'0') instead of (s-'0') so probably its not the case..

somjit{} 60 Junior Poster in Training Featured Poster

'h' is a modifier to the %d specifier, you need them both: "%hd"

yaaaayyy!!

just look at an ASCII table

YAAAAAAAAYYYYYYYYY!!!!!

It means input is an array of 40 objects of size "type". If "type" is char then you have an array of 40 bytes, if "type" is int then you have an array of 40 integers where each one is 4 bytes (going with your assumption). The size of an array of 40 will always be sizeof(type) * 40. Note that sizeof(char) is always 1, and char corresponds to the system's byte size, so an array of 40 char is equivalent to 40 bytes.

MEGA-YAAAAAAAAAAAAAAAAAAAAAYYY!!!!!!!
im marking this thread SOLVED!!

i am happy !! :))

a ton of thanks to you Mr Deceptikon, and Mr waltp!! :)
Thank you!!
:))

oh wait... :(
ip=input[0]

this just takes in one value, so i cant enter double digit numbers here! saw the output... whats the cure for that?? man i was so happy that it working... seems still a little left to go...

somjit{} 60 Junior Poster in Training Featured Poster

yaay! :)
1. code finally runs, no crashing, bypassing.. flows like its supposed to. only tweak i made after the one you posted was adding a

    while(getchar() != 'n')
    { 
        puts("cleaning stdin, if you can see this output, there were more than one whitespace leftout in stdin");

        }

block before the switch-case block, to clean stdin. now it works fine.

just one problem: (they are in love with me it seems..)

  1. i dont get any output for case1 (ie char2shrt()) and case2 (ie int2shrt()).. any ideas on that?
  2. i do get an output for case 3 (ie shrt2int()), but have to work out in binary if its correct or not.

also;
a questions squirming inside mybrain: *type* input[40] means what?

a. input is an array with 40 bytes, thus space for 10 ints(considering int==4bytes), 20 shorts, and 40 chars? or
b. input is an array of 40 blocks of memory, each block==sizeof(type) ,so total memory == *type**40

finally..
my resultant code:

#include<stdio.h>
void char2shrt(void);
void int2shrt(void);
void shrt2int(void);
int main()
{
    char bool=0,op=0;
    int option=0;
    do{
    printf("nnnwhat do you want to do?: n ('1')character to short n ('2')int to short n('3')short to int n press 1,2 or 3:n");
    fflush(stdout);
    scanf("%d",&option);
    //gotta keep stdin clean, scanf() messed it out , so here goes
    while(getchar() != 'n')
    { 
        puts("cleaning stdin, if you can see this output, there were more than one whitespace leftout in stdin");

        }

    switch(option)
        {
        case 1:
            char2shrt();
            break;
        case …
somjit{} 60 Junior Poster in Training Featured Poster

still no cookie...

replaced

short char2shrt(void)
{
    char ip;
    short op;
    printf("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);
}

and then tried 2 things:

1.

short int2shrt(void)
{
    char input[40];
    int *ip;
    short *op;
    printf("enter input:\n");
    while (fgets(input, sizeof(stdin), stdin) && sscanf(input,"%d",ip) == 1)
    {
        printf("You entered %d",*ip);

    }
    *op=(*ip);
    printf("the output in type short is: %h",*op);
}

did not work, loop never ends, keeps giving me

you entered 'blah blah'

then i tried replacing while() like this:

2.

short int2shrt(void)
{
    char input[40];
    int *ip;
    short *op;
    printf("enter input:\n");
    fgets(input,sizeof(stdin),stdin);
    sscanf(input, "%c",ip);
    printf("You entered %c",*ip);
    *op=(*ip);
    printf("the output in type short is: %h",*op);
}

and voila .... program crashes!

i dont know what to do anymore :( can you please correct my code? i know im not supposed to directly ask for code help like this... but i just cant seem to do this... :(

thanks for keeping patience with me...

somjit{} 60 Junior Poster in Training Featured Poster

trying out a new thing.... lets see, ill post once the compilation is done...

somjit{} 60 Junior Poster in Training Featured Poster

i marked this thread as solved, just a question came up in my mind,
@deceptikon:
why use fflush() after every printf() ?

i read Here about fflush() which said if the last i/o operation was an output operation, any unwritten data in the output buffer is written to the stream pointed in fflush(file *stream) , but i fail to understand it in context of these statements that you used above to clarify problems of using gets() after scanf()..

   printf("Enter a number: ");
   fflush(stdout);

any help ?

thanks again
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

major typo : i meant...

but i hope ur not saying "lousy in scanf()==india :P" ..

im sure your not doing that anyways:)

sorry for the weirdness..

somjit{} 60 Junior Poster in Training Featured Poster

Let me guess -- Turbo-C; India. Am I close?

india.. yes :) but i hope ur not lousy in scanf()==india :P
turbo-c >> it was used in our clg labs, but at home > codeblocks+cmd :)
i like the whole geeky feel of programming with green text on a black cmd background :)

back to the good stuff :
this is exerted from your link

int ch;         // define the character
    do              // loop until a good character is read
    {
        ch = getchar();             // read a character
    } while ( (ch == 0x20)  ||      // check for SPACE
             ((ch >= 0x09)  &&      // check for the 
              (ch <= 0x0D))         //    other whitespace
            );              
    return ch;

maybe i can use ch here as a container to hold all the unwanted stuff, and then "delete" them of some sort? is that a good idea? i was thinking like

  1. use malloc to assign space for 'collector' (im renaming 'ch' to collector)
  2. malloc gives more and more space to 'collector' based on length of my input
  3. once all collecting is done, use free to 'delete' it all, and thus keep input buffer clean for next read...

is this a good idea?
my main doubt here being with point number 2... i dont know if malloc can keep appending more space to a variable whose size it has already determined previously...
also, if free can be used in this manner..

as regards the code …

somjit{} 60 Junior Poster in Training Featured Poster

Why would the creator be important?

its just im getting the link from the creator himself.. kinda neat:)

You could have saved yourself a lot of time and trouble by not vaguely reading it the first time, dontcha think?

yeah thats true :( but then i was looking for what scanf() does for my college homework.. and in college they used scanf() for everything!

one thing i would like to ask is that if there is any way i can see exactly whats in stdin?? whitespaces and everything? i read fgets() keeps whitespaces.. what about other ones? does it keep them too?

bdw, the examples in your link really helps :) thanks :)

somjit{} 60 Junior Poster in Training Featured Poster

@waltp : i never looked at the creator of that post before today :) i only looked at it very vaguely once, ill be looking at it in more detail now.

somjit{} 60 Junior Poster in Training Featured Poster

yeah... i saw that mistake i was making when u told about the type... corrected it, well, the problems that were there then have gone now, but a few new ones cropped up :(

corrected code :

#include<stdio.h>
short char2shrt(void);
short int2shrt(void);
int shrt2int(void);
int main()
{
    char bool=0,op=0;
    int option=0;
    do{
    printf("\n\n\nwhat do you want to do?: \n ('1')character to short \n ('2')int to short \n('3')short to int \n press 1,2 or 3:\n");
    scanf("%d",&option);
    switch(option)
        {
        case 1:
            char2shrt();
            break;
        case 2: 
            int2shrt();
            break;
        case 3: 
            shrt2int();
            break;
        }           
    printf("\ndo you wish to iterate once again?yes(1) or no(0):");
    scanf("%d",&bool);
    printf("\npresent state of bool:%d",bool);
    }while(bool==1);

}
short char2shrt(void)
{
    char ip;
    short op;
    printf("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);
}
short int2shrt(void)
{
    int ip;
    short op;
    printf("enter input:\n");
    scanf("%d",&ip);
    op=ip;
    printf("the output in type short is: %h",&op);
}
int shrt2int(void)
{
    short ip;
    int op;
    printf("enter input:\n");
    scanf("%h",&ip);
    op=ip;
    printf("the output in type int is: %d",&op);
}

and this is the output i get :

for_dani_type

problems:
1. for case:1 no user input being taken
2. for case:2 user input being taken, but o/p isnt coming..
3. i am getting an output for case:3, although dont know if its right or wrong ...

any ideas to the weird behaviou for case:1 ??

i think in case:2 output short isnt coming out because the format specifier %h isnt correct?? that short == %h... is what i …

somjit{} 60 Junior Poster in Training Featured Poster

so case: takes only integer? or that im passing char to it in integer format makes it skip the loop altogeher? let me see that... hopefully it will solve this thing! :))

somjit{} 60 Junior Poster in Training Featured Poster

its correct in the hardcopy,checked it, and perhaps, since i copied from the soft version(yeah got too lazy to type there..) that included the mistake, the typo also came in the code, and hence this thread to begin with.. :D

somjit{} 60 Junior Poster in Training Featured Poster

i was watching this video about type conversion and what the compiler does while converting from small byte formats to large byte formats(and vice versa) etc etc, and tried to write a code for it... but seems that function calls in my code are getting completely bypassed...

once again, here goes my sloppy code:

#include<stdio.h>

short char2shrt(void);
short int2shrt(void);
int shrt2int(void);


int main()
{
    char bool=0,option,op=0;
    do{
    puts("what do you want to do?: \n (1)character to short \n (2)int to short \n(3)short to int \n press 1,2 or 3:\n");
    scanf("%c",&option);
    switch(option)
        {
        case 1:
            char2shrt(void);
            break;
        case 2: 
            int2shrt(void);
            break;
        case 3: 
            shrt2int(void);
            break;
        }           
    puts("\ndo you wish to iterate once again?yes(1) or no(0):");
    scanf("%d",&bool);
    printf("\npresent state of bool:%d",bool);
    }while(bool==1);
}


short char2shrt(void)
{
    char ip;
    short op;
    puts("enter input:\n");
    scanf("%c",&ip);
    op=ip;
    printf("the output in type short is: %h",op);

}

short int2shrt(void)
{
    int ip;
    short op;
    puts("enter input:\n");
    scanf("%d",&ip);
    op=ip;
    printf("the output in type short is: %h",&op);
}

int shrt2int(void)
{
    short ip;
    int op;
    puts("enter input:\n");
    scanf("%h",&ip);
    op=ip;
    printf("the output in type int is: %d",&op);
}

the attepmts i made were as such:

  1. 1st created the functions akin to void foo(void) , that didnt work, then i tried making them like some_type foo(void) that didnt work either

  2. i thought making somthing like

    switch(option)
    {
    case 1:
    op=char2short(void);
    printf("the output in type short is: %h",op);
    break;
    .
    .

with "op" declared as char in the begining, and …

somjit{} 60 Junior Poster in Training Featured Poster

@deceptikon : u make it so easy :) thanks.. found it :)
it should be c=='\t'
i also now get what waltP was saying..
sorry to trouble u guys with such silly things. should have paid more attention.

thanks again :)
somjit.

somjit{} 60 Junior Poster in Training Featured Poster

i checked both my pdf and hardcopy with the code i posted, and its the same!!
for_dani_web

this is the output im getting... word count=0 , others (line count=1, character count=23) seems to be doing fine.

I velieve if you look closer, there is either an error or warning for that line.

i read that || is left-to-right operator, and i also tried putting each of the conditions in bracket to eliminate any problems due to matters of precedence and priority... but still i get the same result.

somjit{} 60 Junior Poster in Training Featured Poster

Your code doesn't look like the code in the book

i copy pasted from the book and not from my programmer window just to be sure. perhaps copying from a pdf file included some errors. let me check with my hardcopy once more...

What do you see that's not consisent?

the count for line, and character are coming out fine, but the count for new word is always showing 0.

somjit{} 60 Junior Poster in Training Featured Poster

this is a code from the book "the C programming language" by dennis ritchie, but for some reason its not working!

#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}

the output shows "nw" (for NewWord) as 0 all the time..
cant understand why this is so...

somjit{} 60 Junior Poster in Training Featured Poster

deceptikonfacepalm :D

thankyou so much for the superfast reply @deceptikon :) i completely forgot about strcopy!!
thank you. problem solved :) u rock :)

somjit{} 60 Junior Poster in Training Featured Poster

i want to take the 1st argument from commandline, ie argv[1] and assign it to a char target[80]

i know im making some very stupid beginer mistakes... but just cant understand what :(

this is my code:

#include <stdio.h>
#include <string.h>
void converge(char *targ, char *src);
int main(char *argc[],char *argv[])
{
char target[80];
target=(*argv[1]);
converge(target, "This is a test of converge().");
printf("Final string: %s\n", target);
printf("%s",argv[1]);
return 0;

}
/* This function copies one string into another.
It copies characters to both the ends,
converging at the middle. */
void converge(char *targ, char *src)
{
int i, j;
printf("%s\n", targ);
for(i=0, j=strlen(src); i<=j; i++, j--) {
targ[i] = src[i];
targ[j] = src[j];
printf("%s\n", targ);
}
}

and all the problems are coming from this line target=(*argv[1]);

would be great if anyone could help on how this should work, and why this isnt working..
thanks in advance. :)
somjit

somjit{} 60 Junior Poster in Training Featured Poster
@deceptikon

brother's wedding going on, that, coupled with him letting me play with his leica m8 while he's busy being the groom is turning out to a major distraction. :D its the reason for this late reply.

and regarding ur post, thank you so so much!! i tried to understand what that page was saying abt fflush being bad and all but wasnt very successful. u made it so much clearer!! thanks a lot! :) will be getting back to C within the end of the week . :) thanks for helping me out with such detailed answers and explanations :) really really helpful this was.

regards
somjit.

somjit{} 60 Junior Poster in Training Featured Poster
@WaltP

And the exact same thing goes for using scanf() to read strings. It's as bad as gets().

yeah i read that scanf() for reading strings was a bad thing to do.. that why started with gets(). im reading into fgets() now. :) thanks for the help :)

somjit{} 60 Junior Poster in Training Featured Poster
@ banfa

To start with scanf("%s",&sh); is incorrect it should be scanf("%s",sh); because sh is an array so using it without any [] already produces a pointer to it, you don't need to de-reference it.

Secondly, never, ever use gets, always use fgets, so not gets(sh); but fgets(sh, sizeof sh, stdin); it is safer since you can't overwrite the buffer, but note that gets does not return the '\n' at the end of the line and fgets does.

thanks for pointing them out :)
also thanks for the neat n trim analysis of my problem there :)

somjit{} 60 Junior Poster in Training Featured Poster
@deceptikon

thanks a lot for those example codes :) but as i was going through them.. u showed the use of fflush(stdout). a bit confusion here, coz i read [in this page](http://www.gidnetwork.com/b-57.html) that using fflush is a bad thing. although they only mentioned it for the case of fflush(stdin).

the page said

You've been programming for a couple years now and are in the habit of flushing stdin because you always use scanf() (another function you should avoid*). You get a new job that has a compiler without this particular enhancement. Your programs no longer work. You will spend days trying to figure out what's wrong because you 'know' fflush() can't be the problem -- you've used it for years.

does the same thing apply for flushing output stream as you had shown??

somjit{} 60 Junior Poster in Training Featured Poster
code to convert any base input to any base output (base limited upto hexadecimal)
scanf() works , but gets() stops working from 2nd iteration

i apolozise beforehand for the length of this post, i hope there will be someone who'll bear with me :(

here is my code, the one with scanf(). this one has no problems and works just fine. :)

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


int entry();// gets any base input and converts it to decimal

int main(void){

int ip_num,ip_base,op_num,op_base,i=0,cont_flag,acc[20];

char base_digits[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

do{
ip_num=entry();

printf("choose the base to convert to:");
scanf("%d",& op_base);


puts("\nin main()\n\nexecuting for() loop . . .\n\n");
for(i=0;i<20 && ip_num!=0;i++) // converts to required o/p base
{

acc[i]=(ip_num % op_base);
ip_num=ip_num/op_base;
printf("index: %d \n",i);

if(ip_num==0)
break;

if(i==19) {
puts("array acc[] full");
break;
}

}//end of for()

printf("\nconverted number in base %d is:",op_base);

for(i;i>=0;i--)// prints the number 
{
printf("%c",base_digits[acc[i]]);
}

printf("\n\n convert another number? press\n 1(yes)\n 0(no)\n:");
scanf("%d",& cont_flag);
}while(cont_flag==1);
}


int entry()
{
 char sh[100],*stop;
 int ip_num,ip_base;
printf("Enter a number: ");
scanf("%s",&sh);

printf("enter radix: ");
scanf("%d",&ip_base); 

 ip_num = strtol(sh,&stop,ip_base);
 return(ip_num);
}

everything works fine. entry() has an strtol() function in its heart that converts any input to decimal, and then the main() takes that decimal and converts it to the desired base , as indicated by op_base.

THE ONLY PROBLEM :

its when i change entry() in the following manner:

int entry()
{
 char sh[100],*stop;
 int ip_num,ip_base;
printf("Enter a number: ");
gets(sh);

printf("enter radix: ");
scanf("%d",&ip_base); 

 ip_num = strtol(sh,&stop,ip_base);
 return(ip_num);
}

the …