multiple printf of same array element

array blues

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1680 Views - Last Post: 02 May 2010 - 10:47 AM Rate Topic: -----

#1 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

multiple printf of same array element

Posted 29 April 2010 - 11:28 AM

this is a homework assignment (just putting it out there)

What I am trying to do concerns practice with signals. I am using SIGINT and have created a signal handler that prints out a statement. (There's also a loop that gets interrupted).

Here is the code:

/* sigdemo1.c
 * shows how a signal handler works.
 * -run this and press ctrl-c a few times
 */
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <termios.h>
#define QUESTION "Are you sure you want to quit?"
#define MAX 10

void f(int sig);//Signal handler declaration
void loop(void);//Looping function declaration

int main(void){
    signal(SIGINT, f);
    for (;;)/>{
        loop();
    }
    return 0;
}
//Signal Handler
void f(int sig){
    int i;
    char b[] = {'!'};
    char answer[MAX];
    //this is what I want to do:
    //for every interrupt append a bang symbol
    for(i=0; i<10; i++){
    //printf("OUCH!\n");
        if (i=1){
            printf("OUCH%s\n",B)/>;
        
        //if(i=2){
        //    printf("OUCH%s\n",b[1]);
        //}
    
    printf("Interrupt: (%d) received\n\n", sig);
        }
    }
    printf(QUESTION);
    scanf("%s", answer);
        if (*answer == 'n'){
            signal(SIGINT, f);
        }
        else
        exit(1);
   }

//Looping segment (infinite)
void loop(void){
    printf("I am alive! HELLO!\n");
    sleep(1);
}



The problem I run into is how to append the same array element (plus 1) every time the interrupt occurs. I have variants (none of them work of course). What am I missing?


Thank you (sorry for the title screw up)

This post has been edited by jinx3y: 29 April 2010 - 11:29 AM


Is This A Good Question/Topic? 0
  • +

Replies To: multiple printf of same array element

#2 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: multiple printf of same array element

Posted 29 April 2010 - 11:38 AM

You have two errors in the code you have posted. The errors are corrected here:

    //printf("OUCH!\n");
        if (i==1){                //<<< i=1 is an assignment ... correct to i == 1 which is a test
            printf("OUCH%s\n",B)/>; //<<< B not declared ... you meant b



The code then runs and signals correctly.
Was This Post Helpful? 0
  • +
  • -

#3 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: multiple printf of same array element

Posted 29 April 2010 - 01:12 PM

I appreciate the help I added the additional = and it worked.

The "B" i think was a copy error into the posting (my original code is a "b")

That still leaves the problem with how to append an extra "!" every time an interrupt is handled...
Was This Post Helpful? 0
  • +
  • -

#4 noclaf  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Re: multiple printf of same array element

Posted 29 April 2010 - 01:19 PM

A static global variable is the only thing that fits your requirements. Something like...

static int int_count = 0;
....

void f(int sig) {
  int_count++;
  printf("OUCH");
  
  int i;
  for (i = 0; i < int_count; i++)
    putchar('!');
  putchar('\n');
...
}

This post has been edited by noclaf: 29 April 2010 - 01:19 PM

Was This Post Helpful? 0
  • +
  • -

#5 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: multiple printf of same array element

Posted 30 April 2010 - 11:39 AM

I appreciate the help guys. it got me a long way but the code was still not producing the output I needed. I thought perhaps using strcat in a while loop to append an extra "!" might work but all that happens now is that the program terminates.

So far, this has been the output:

PC1 ~/415/sigdemo
$ ./a
I am alive! HELLO!
I am alive! HELLO!
I am alive! HELLO!
OUCH!
Interrupt: (2) received

Are you sure you want to quit?n
I am alive! HELLO!
I am alive! HELLO!
I am alive! HELLO!
I am alive! HELLO!
OUCH!
Interrupt: (2) received

Are you sure you want to quit?y

PC1 ~/415/sigdemo
$



This is what I have


/* sigdemo1.c
 * shows how a signal handler works.
 * -run this and press ctrl-c a few times
 */
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <termios.h>
#define QUESTION "Are you sure you want to quit?"
#define MAX 3


static int count = 0;//static global variable
void f(int sig);//Signal handler declaration
void loop(void);//Looping function declaration
/*void append(char* s, char c){
    int len=strlen(s);
    s[len] = c;
    s[len+1] = '\0';
}
*/
int main(void){
    signal(SIGINT, f);
    for (;;)/>{
        loop();
    }
    return 0;
}
//Signal Handler
void f(int sig){//open f function
    int i = 0;//initialize i
    char answer[MAX];//maximum no of characters to accept for MAX
    int count = 0;//initialize count variable
    count++;//increment count
    
    char a[] = {'!', '\0'};//character array a[] with bang symbol loaded
    char *aptr;//pointer for a[]
    aptr = &a[0];//assigning aptr to a[] first element
    
    char b[5] = "OUCH";//character array b[] with "OUCH" preloaded
    
            
    for (i=0; i<count; i++)//for loop start
        while (i < count && i > 0){
            strcat(a, aptr);//close while loop//supposed to append an extra "!" to a[]
        }//close while loop
        printf("%s%s\n",b,a);//print "OUCH" and a[] for each use of ctrl-C
        printf("Interrupt: (%d) received\n\n", sig);//print interrupt signal code
        
        printf(QUESTION);
        scanf("%s", answer);
            if (*answer == 'n'){//if n is typed...
                signal(SIGINT, f);//...continue running the looping segment
            }
            else//otherwise...
            exit(1);//...terminate the program
   
}//close for loop

//Looping segment (infinite)
void loop(void){
    printf("I am alive! HELLO!\n");
    sleep(1);//pause between each new line
}
 



I know I am on the right track, I am just not understanding why strcat isn't doing the job. Maybe I've been at this for too long...lol
Was This Post Helpful? 0
  • +
  • -

#6 noclaf  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Re: multiple printf of same array element

Posted 30 April 2010 - 12:00 PM

You're trying to cat a '\0' after every ! -- printf is going to stop reading at the first '\0' regardless of what's after it. strcat (which I don't believe is the proper solution for adding a single character at a time) will add its own null terminator to the end of the string.

Why are you redeclaring the variable 'count' inside the sig handler? This is counter productive to maintaining the number of SIGINTs you receive.

Was there an issue with the solution I provided?
Was This Post Helpful? 0
  • +
  • -

#7 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: multiple printf of same array element

Posted 01 May 2010 - 05:48 AM

I relooked at the solution you provided (i found that I mistyped when i should have just copied and pasted). It does add the extra !. Thanks. I just have to go through and position it correctly so that it displays immediately after the OUCH.

Thanks

This post has been edited by jinx3y: 01 May 2010 - 07:50 AM

Was This Post Helpful? 0
  • +
  • -

#8 noclaf  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Re: multiple printf of same array element

Posted 01 May 2010 - 06:59 AM

View Postjinx3y, on 01 May 2010 - 04:48 AM, said:

putchar placed the ! on the next line and did not add an extra ! for each interrupt (it wasn't concatenating with the OUCH. More than likely it was my mistake (admittedly, programming is not my best subject, but I recognize it's significance and so, push myself hard through the courses). I will keep trying (and use your suggestion) and see where I went wrong. I will display the code here whether or not I get it right.

Thank you

putchar doesn't do anything but write a single char to stdout. If it wasn't being tacked onto the end of the 'OUCH' then you had a newline character at the end of that string. Below is a small example that illustrates the usage of that code snippet.

#include <stdio.h>
#include <signal.h>

static int sigcount = 0;

void sighandler(int sig) {
  sigcount++;

  int i;
  printf("OUCH");
  for (i = 0; i < sigcount; i++)
    putchar('!');
  putchar('\n');
}

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

  signal(SIGINT, sighandler);

  while (1) {
    printf("sleeping...\n");
    sleep(2);
  }

  return 0;
}

Was This Post Helpful? 0
  • +
  • -

#9 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: multiple printf of same array element

Posted 01 May 2010 - 07:43 AM

View PostMartyn.Rae, on 29 April 2010 - 01:38 PM, said:

You have two errors in the code you have posted. The errors are corrected here:

    //printf("OUCH!\n");
        if (i==1){                //<<< i=1 is an assignment ... correct to i == 1 which is a test
            printf("OUCH%s\n",B)/>; //<<< B not declared ... you meant b



The code then runs and signals correctly.


@Martyn: Just some "FYI" -- DIC was the one who converted the b to a B - this is a bug in the forum software, it will always convert b) into B) so that it becomes this: B). So if you see code with B) in it and no B defined, the safe bet is DIC put the B there. Also, if you try to post "corrected" code, make sure you put a space between the b and the ) else you end up with the same problem in your code!

This is a really irritating bug that I have brought up several times... personally I have found that I have begun to avoid using examples that use b as a variable because of it.
Was This Post Helpful? 0
  • +
  • -

#10 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: multiple printf of same array element

Posted 01 May 2010 - 09:57 AM

Thanks...I'll remember that one.

Next part:

It all works as needed you can compile it and check. (thanks largely to noclaf)
Next problem: accepting command line arguments that can limit the amount of times it accepts interrupts. Basically, <program name> <number of iterations>. I am trying to work through this with only partial understanding, I think. What I know is that you can't equate a string to an integer without using atoi.

How do I get the second value of *argv[] (which would be the iteration parameter) to return as an integer for use in a loop? (I really feel like I'm climbing Mt. Everest with this...lol)

Here's the code:


#include <string.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <termios.h>
#define QUESTION "Are you sure you want to quit? "
#define MAX 3


static int count = 0;           //static global variable
void f(int sig);                //Signal handler declaration
void loop(void);                //Loop function declaration
//void run(void);

int main(void){
    signal(SIGINT, f);
    for (;;)/>{
        loop();
    }
    return 0;
}
//commented out section to allow rest of the program to function - here's my "screw up" part
/*int main(int ac, char *av[]){
    
    scanf ("%s %d",&av[0], &av[1]);
    int b;
    //int *a;
    //a = &av[1];
    if (ac != 2 ){
        printf("Error at command line input.\n"
                "Proper usage is:\n"
                "<program_name> <#of times to accept interrupt (a greater than zero value)>\n"
                "av[0]:%s  av[1]:%s  ac:%s",av[0],av[1],ac);
        
    }
    if (&av[1] = 0){                 //no funny business...
        printf("In order for this program to demonstrate signal handling,\n"
            "you have to at least let it run once.  Enter a number greater\n"
            "than zero in the command line argument.");
    }
    else
    if (ac = 2){
        while (&av[1] != 0){
            for ( b = 0; b < &av[1]; b++ ){       //set up iterated for loop
            signal(SIGINT, f);                        
                loop();                         //do the loop() function b times
            }
            return 0;
        }
    }
}
*/
//Signal Handler
void f(int sig){                //start of f function
    int i;                      //initialize i
    char answer[MAX];           //maximum no of characters to accept for answer
    count++;                    //post-increment count
    printf("OUCH");             //print this, no newline
    for (i = 0; i < count; i++) //loop allowing for append of bang symbol to end of OUCH
        putchar('!');           //print the character "!"
    putchar('\n');              //print newline

    printf("Interrupt: code(%d) received\n\n", sig);    //print interrupt signal code
    printf(QUESTION);                                   //are you sure?
    scanf("%s", answer);                                //scan next input
        if (*answer == 'n'){                            //if "n" typed...
            signal(SIGINT, f);                          //...continue running the looping segment
        }
        else                                            //otherwise...
            exit(1);                                    //...terminate the program
}

//Looping segment (infinite)
void loop(void){
    printf("I am alive! HELLO!\n");                     //output to stdout
    sleep(1);                                           //pause between each new line
}


Was This Post Helpful? 0
  • +
  • -

#11 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: multiple printf of same array element

Posted 01 May 2010 - 09:59 AM

Use strtol.
Was This Post Helpful? 0
  • +
  • -

#12 noclaf  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Re: multiple printf of same array element

Posted 01 May 2010 - 10:58 AM

View Postjinx3y, on 01 May 2010 - 08:57 AM, said:

...
        while (&av[1] != 0){
            for ( b = 0; b < &av[1]; b++ ){       //set up iterated for loop
            signal(SIGINT, f);                        
                loop();                         //do the loop() function b times
            }
            return 0;
        }
...
        if (*answer == 'n'){                            //if "n" typed...
            signal(SIGINT, f);                          //...continue running the looping segment
        }
        else                                            //otherwise...
            exit(1);                                    //...terminate the program
...


Your usage of the signal() function is wrong in both these cases here (albeit benign). signal() is used to define the behavior exhibited when a given signal is received. Unless you're redefining behavior differently, it should never need to be called more than once for any given signal.

This post has been edited by noclaf: 01 May 2010 - 10:58 AM

Was This Post Helpful? 0
  • +
  • -

#13 jinx3y  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 34
  • Joined: 27-April 10

Re: multiple printf of same array element

Posted 02 May 2010 - 05:10 AM

got it..removed it and replaced signal function with "loop();"
I have to turn in the project today so I am out of time with it.

It compiles without incident under cygwin using gcc but upon execution I get a segmentation fault. I have tried to figure out where it is I am doing illegal memory operations but I just don't see it. I have further added the strtol function to convert argument 2 (av[1]) to a long int for use in a loop.

Here is the code:


int main(int ac, char *av[]){
    const char *s;
    long li;
    s = av[1];                              //assign s to 2nd parameter (av[1])
    li = strtol(s, NULL, 0);                //converts string at av[1] to long int
    int b;

    if (ac != 2 ){                          //parameter check 1
        printf("Error at command line input.\n"
                "Proper usage is:\n"
                "<program_name> <#of times to accept interrupt (a greater than zero value)>\n");
                //"av[0]:%s  av[1]:%s  ac:%s",av[0],av[1],ac);
        //exit(1);
        
    }
    if (li = 0){                            //parameter check 2 (no funny business...)
        printf("In order for this program to demonstrate signal handling,\n"
               "you have to at least let it run once.  Enter a number\n"
               "greater than zero in the command line argument.");
        //exit(1);
    }
    else
    if (ac = 2){                            //parameter check 3 in else
        while (li != 0){                    //condition
            for (b = 0; b <= li; b++){       //set up iterated for loop
            signal(SIGINT, f);
                loop();                     //do the loop() function
            }
            return 0;
        }
    }
}




The rest of the code is listed somewhere back up in the earlier posts.

I appreciate all the help..

Thanks
Was This Post Helpful? 0
  • +
  • -

#14 janotte  Icon User is offline

  • code > sword
  • member icon

Reputation: 990
  • View blog
  • Posts: 5,141
  • Joined: 28-September 06

Re: multiple printf of same array element

Posted 02 May 2010 - 05:21 AM

View Postjinx3y, on 02 May 2010 - 09:10 PM, said:

The rest of the code is listed somewhere back up in the earlier posts.


I did start to look at your code then I thought if you can't be bothered to collect all your code into one place to make it easy for me (us) to help you why should I be bothered to try and reconstruct, by partial guesswork, what state your full code might now be in.

Please post your full code as it is and let's see if we can help you with you seg fault.
Was This Post Helpful? 0
  • +
  • -

#15 noclaf  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 94
  • Joined: 18-April 10

Re: multiple printf of same array element

Posted 02 May 2010 - 06:43 AM

View Postjinx3y, on 02 May 2010 - 04:10 AM, said:

got it..removed it and replaced signal function with "loop();"
I have to turn in the project today so I am out of time with it.

It compiles without incident under cygwin using gcc but upon execution I get a segmentation fault. I have tried to figure out where it is I am doing illegal memory operations but I just don't see it. I have further added the strtol function to convert argument 2 (av[1]) to a long int for use in a loop.

Here is the code:


int main(int ac, char *av[]){
    const char *s;
    long li;
    s = av[1];                              //assign s to 2nd parameter (av[1])
    li = strtol(s, NULL, 0);                //converts string at av[1] to long int
    int b;

    if (ac != 2 ){                          //parameter check 1
        printf("Error at command line input.\n"
                "Proper usage is:\n"
                "<program_name> <#of times to accept interrupt (a greater than zero value)>\n");
                //"av[0]:%s  av[1]:%s  ac:%s",av[0],av[1],ac);
        //exit(1);
        
    }
    if (li = 0){                            //parameter check 2 (no funny business...)
        printf("In order for this program to demonstrate signal handling,\n"
               "you have to at least let it run once.  Enter a number\n"
               "greater than zero in the command line argument.");
        //exit(1);
    }
    else
    if (ac = 2){                            //parameter check 3 in else
        while (li != 0){                    //condition
            for (b = 0; b <= li; b++){       //set up iterated for loop
            signal(SIGINT, f);
                loop();                     //do the loop() function
            }
            return 0;
        }
    }
}




The rest of the code is listed somewhere back up in the earlier posts.

I appreciate all the help..

Thanks

The third argument of strtol() is the base you want to convert to. I think you may have left off the '1' when you went to put '10' in there.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2