LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C Beginner Help Plz :D (https://www.linuxquestions.org/questions/programming-9/c-beginner-help-plz-d-373243/)

InvisibleSniper 10-15-2005 03:46 AM

C Beginner Help Plz :D
 
Hi again,

I seem to be having a bit of trouble with some of the code I wrote. I am only new at C and this code has arrays and pointers to structures. I know what what part is wrong in it and it is the part where the user is supose to enter his/her name. I would like to store their name in an array, the reason behind the 2D array I have used is because later I will be adding more names; but I do not know what element to store the name in or even how to go about it. This code I have written is only for practic so if it doesn't make any sense to do some of the things I have done that's ok, it's just the run-time error I would like to remove, please :D

Here is my code:
Code:

#include<stdio.h>

struct employee{

int age;
char name[100][15];
};

int main()
{

struct employee *empP;



empP->age = 56;
/*
*
*Accept the user's name
*/as input.
printf("Please enter your name: ");
scanf("%[^\n]", empP->name[0][0]);


printf("The age of structure *empP is: %d", empP->age);
/*
*
*Print out the user's name
*/
printf("\nYour name is: %s",empP->name[0][0]);*/Print out the user's name*/
fflush(stdin);


getchar();


}

Thanks for your help.

jlliagre 10-15-2005 04:28 AM

1: your code has typos, fix them first (posted code should compile)
2: you are using empP without initializing it
3: compile with -Wall and fix anything gcc complains of

InvisibleSniper 10-15-2005 05:07 AM

Quote:

Originally posted by jlliagre
1: your code has typos, fix them first (posted code should compile)
2: you are using empP without initializing it
3: compile with -Wall and fix anything gcc complains of

My code compiles fine but it is a run-time error. I don't know exactly how to initialise an array yet though, I am going to go and learn now.

sind 10-15-2005 06:38 AM

Expanding on jlliagre's post, the reason why your program isn't working (I would guess that you're getting a segmentation fault / access violation) is that you haven't initialised empP, which is a pointer to a struct of type "employee".

You either need to change your declaration of empP so that it refers directly to an "employee" structure:

Code:

struct employee empP;

empP.age = 56; /* Notice the different operator to access "age" */

Or allocate memory on the free store/heap for an "employee" structure:

Code:

struct employee *empP = NULL;

/* Allocates memory for an employee struct, and puts the address
  of that memory into empP */
empP = malloc(sizeof(struct employee));

/* Sets each byte of the struct pointed to by empP to 0, so that it
  is in a known state */
memset(empP, 0, sizeof(struct employee));

empP->age = 56;

/* Rest of code */

/* When finished with empP, the memory should be freed */
if (empP != NULL)
{
    free(empP);
    empP = NULL;
}

Remember that a structure has to "be" somewhere for you to be able to use it. A pointer is just a variable that holds an address; you need to "make" somewhere for the struct first and tell the pointer to point to that area.

~sind

InvisibleSniper 11-02-2005 01:23 AM

Hi again,

I wanted to use some code that basically did this:
Code:


/*Check to see if the user entered any one of the data types (any one is ok)
* and if not the repeat the question to get the right type
*/
if (*hrs_worked_tdy != float || *hrs_worked_tdy != int || *hrs_worked_tdy != double)
{
//CODE BELOW
}

So in other words I want an If statement that checks to see if the variable "hrs_worked_tdy" is any of the following; an "Integer", a "Double" or a "Float". And if not then to execute the code below.

::EDIT::

I have now added this to see if it works but it still doesn't:
Code:

if (isalpha(*hrs_worked_tdy) || ispunct(*hrs_worked_tdy))

Here is my entire code:
Code:

#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
#define HOURLY_PAY 15.00
#define ONE_HOUR 60
#define PAY_OUPUT_DIR "C:\\Documents and Settings\\MasterSpotty\\My Documents\\Output_Pay.txt"

void get_user_input(float *hrs_worked_tdy)
{
for(;;)
/*No condition loop*/
{
 printf("\nPlease enter how many hours you worked today.");
 printf("\nEnter the hours you worked in the form of (1.5hrs): ");
 scanf("%f", *&hrs_worked_tdy);
 fflush(stdin);
            if (isalpha(*hrs_worked_tdy) && ispunct(*hrs_worked_tdy))
            {
            printf("\nSorry... you have entered incorrect information. Please re-enter");
            printf("\ndata and try again.");
            continue;
              }
            break;
}

}



int main()
{
FILE *wrk_fptr;
float hrs_wrked_tdy;
get_user_input(&hrs_wrked_tdy);

wrk_fptr = fopen(PAY_OUPUT_DIR, "w");
if(wrk_fptr == NULL)
{
printf("\nSorry, can not open %s. Program terminating...",PAY_OUPUT_DIR);
exit(1);
}

fprintf(wrk_fptr, "\nYou worked %2.f hours.", hrs_wrked_tdy);


fclose(wrk_fptr);

fflush(stdin);
getchar();







}


Wim Sturkenboom 11-02-2005 02:22 AM

Please indicate what the problem is. I guess it does not compile without errors / warnings.

2 things I see:

check the man page for the is.... family (isalpha etc); these functions take a char and not a number

your function get_user_input takes a pointer to hrs_worked_tdy; next, in the call to scanf you pass the address of this pointer (so pointer to pointer)

InvisibleSniper 11-03-2005 09:13 AM

It compiles and runs. All I want it to do now is check if the user entered a "grammatical character" or a "number". This is why it's like this:

Code:

if (isalpha(*hrs_worked_tdy) && ispunct(*hrs_worked_tdy))

naf 11-03-2005 04:34 PM

If you want to check for a number, use isdigit:

Code:

if( isdigit(*hrs_worked_tdy) )
If you want to check that it is only a number:
Code:

char *ptr;
double number;

for( ptr = hrs_worked_tdy; *ptr; ptr++ )
    if( ! ( isdigit( (int)( *ptr ) ) || ( *ptr == '.' ) ) )
        break;

if( *ptr )
    ; /* Bad number! */

number = strtod( hrs_worked_tdy, 0 );


InvisibleSniper 11-03-2005 06:58 PM

I tried using the "isdigit" function like this below:

Code:

#include<stdlib.h>
#include<stdio.h>
#include<ctype.h>
#define HOURLY_PAY 15.00
#define ONE_HOUR 60
#define PAY_OUPUT_DIR "C:\\Documents and Settings\\InvisibleSniper\\My Documents\\Output_Pay.txt"

void get_user_input(float *hrs_worked_tdy)
{
for(;;)
/*No condition loop*/
{
 printf("\nPlease enter how many hours you worked today.");
 printf("\nEnter the hours you worked in the form of (1.5hrs): ");
 scanf("%f", *&hrs_worked_tdy);
 fflush(stdin);
            if (isdigit(*hrs_worked_tdy))
            {
            printf("\nSorry... you have entered incorrect information. Please re-enter");
            printf("\ndata and try again.");
            continue;
              }
            break;
}

}



int main()
{
FILE *wrk_fptr;
float hrs_wrked_tdy;
get_user_input(&hrs_wrked_tdy);

wrk_fptr = fopen(PAY_OUPUT_DIR, "w");
if(wrk_fptr == NULL)
{
printf("\nSorry, can not open %s. Program terminating...",PAY_OUPUT_DIR);
exit(1);
}

fprintf(wrk_fptr, "\nYou worked %2.f hours.", hrs_wrked_tdy);


fclose(wrk_fptr);

fflush(stdin);
getchar();







}

But it still doesn't work, the output always evaluates to true and the body of the if statement always gets executed for some reason. Isn't there some way I could just test the isdigit function for a boolean like the following:
Code:

if(isdigit(*hrs_wrked_tdy) == 1)
/*DO
*STUFF
*/


naf 11-03-2005 11:05 PM

Well your usage there is saying "iif the first character is a digit, then complain". I don't think that is what you meant.
You want to see if the whole number is valid (all digits or period). Your if should have a ! symbol to dinicate not digiti.

Wim Sturkenboom 11-04-2005 06:42 AM

If I compile using g++ -Wall testje.c -o testje,
it tells me:
Code:

testje.c:17: warning: passing 'float' for argument passing 1 of 'int isalpha(int)'
testje.c:17: warning: argument to 'int' from 'float'

BTW, I expected the same warning as well with gcc, but that did not happen :scratch:

As stated in my earlier post, is.... functions check a character and not a float

naf 11-04-2005 07:31 AM

The problem is clear to me now. You are reading in a float and trying to see if it valid? There is no way because you just relied on scanf to do so.
However, if you read the value in as a string, validate the characters and finally convert it to a float or double, then you can do validation of non-number values. Most likely, scanf will work like strtod where invalid characters are ignored and considered the end of the value so entering "ha" = 0.

InvisibleSniper 11-04-2005 10:00 AM

Quote:

Originally posted by naf
The problem is clear to me now. You are reading in a float and trying to see if it valid? There is no way because you just relied on scanf to do so.
However, if you read the value in as a string, validate the characters and finally convert it to a float or double, then you can do validation of non-number values. Most likely, scanf will work like strtod where invalid characters are ignored and considered the end of the value so entering "ha" = 0.

Mmmm, ok thanks for that, the only problem now is that I need to make pointers to arrays if I was to use "scanf" to read the user's input into a string and then "cast" the string into a "float". And I've never made pointers to arrays :)

naf 11-04-2005 10:34 AM

I just like using doubles (better precision) instead of float personally, but you can change it to float just as well.
Code:

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

#define HOURLY_PAY 15.00
#define ONE_HOUR 60
#define PAY_OUPUT_DIR "Output_Pay.txt"

void get_user_input( double *hrs_worked_tdy );

int main( int argc, char **argv )
{
        FILE *wrk_fptr;
        double hrs_wrked_tdy;

        get_user_input( &hrs_wrked_tdy );

        if( ! ( wrk_fptr = fopen( PAY_OUPUT_DIR, "wt" ) ) )
        {
                printf( "\nSorry, can not open %s. Program terminating...", PAY_OUPUT_DIR );
                exit( 1 );
        }

        fprintf( wrk_fptr, "\nYou worked %2.f hours.", hrs_wrked_tdy );

        fclose( wrk_fptr );

        fflush( stdin );
        getchar();

        return 0;
}

void get_user_input( double *hrs_worked_tdy )
{
        char buffer[128];
        char *ptr;

        /* No condition loop */
        for( ; ; )
        {
                /* Write a prompt. */
                printf( "\n"
                        "Please enter how many hours you worked today.\n"
                        "Enter the hours you worked in the form of (1.5hrs): " );

                /* Get a line of text. */
                fgets( buffer, 128, stdin );

                /* Validate the number. */
                for( ptr = buffer; *ptr && ( *ptr != '\n' ); ptr++ )
                        if( ! ( isdigit( (int)( *ptr ) ) || ( *ptr == '.' ) ) )
                                break;        /* Value was bad. */

                /* Was valid (i.e. end reached in scan)? */
                if( *ptr == '\n' )
                {
                        *hrs_worked_tdy = strtod( buffer, 0 );
                        break;
                }

                /* Report error to user. */
                printf( "\n"
                        "Sorry... you have entered incorrect information. Please re-enter\n"
                        "data and try again." );
        }
}


itz2000 11-05-2005 05:25 AM

Quote:

C:\\Documents and Settings\\InvisibleSniper\\My Documents\\Output_Pay.txt
WINDOWS USER ALERT!

change it to :
file:///home/user/

:]]

J/King


All times are GMT -5. The time now is 10:20 AM.