COKEDUDE 27 Junior Poster in Training

Can someone please remind me what "->" means and how to use it.

COKEDUDE 27 Junior Poster in Training

And you point is???

The point is to help people that are not C experts that have all of this memorized.

COKEDUDE 27 Junior Poster in Training

Here is a good listing of library functions.
http://www.cplusplus.com/reference/clibrary/cstring/

jephthah commented: WOO HOO! +7
COKEDUDE 27 Junior Poster in Training

Ok I have 3 parts. I really can't figure out what my problem is. My current warnings are below.
variables.c: In function âset_variableâ:
variables.c:35: warning: initialization from incompatible pointer type
variables.c: In function âvariable_valueâ:
variables.c:66: warning: control reaches end of non-void function
variables.c: At top level:
variables.c:18: warning: ânodeâ defined but not used

I also get a segmentation fault which I believe is usually caused by pointer problems. I'm not sure how to fix it.

dictionary.c

#include <stdio.h>
#include "variables.h"

void verify (double result, double expected_value)
{
    if (result != expected_value)
    {
        printf ("Incorrect result.  Should be %8.4f\n\n", expected_value);
    }
}

int main()
{
    double result;

    printf ("Starting dictionary test\n\n");
    set_variable("A1", 1.0);
    set_variable("A2", 2.0);
    set_variable("A3_3333", 3.3333);

    result = variable_value("A1");
    printf ("A1 is %8.4f.\n", result);
    verify(result, 1.0);

    result = variable_value("A2");
    printf ("A2 is %8.4f.\n", result);
    verify(result, 2.0);

    result = variable_value("A3_3333");

    printf ("A3_333 is %8.4f\n", result);
    verify(result, 3.3333);

    set_variable("A long variable", -1.0);
    result = variable_value("A long variable");
    printf ("A long variable is %8.4f\n", result);
    verify(result, -1.0);

    result = variable_value("Unset Variable ");
    printf ("Unset Variable  is %8.4f\n", result);
    verify(result, 0.0);

    printf ("\n");
    printf ("All variables:\n");
    display_variables();

    printf ("Dictionary test complete\n");
    getchar();
    return 0;
}

*****************************************************************************
variables.h

#define MAX_VARIABLE_LENGTH 15

/* Set the variable with the specified name to the specified value.
 * If there is not a variable with that name in the dictionary,
 * add one. */
void set_variable (const char* name, double value);


/* Return the value of the variable …
COKEDUDE 27 Junior Poster in Training

You have to create the functions:
set_variable()
variable_value()
and
display_variables()
in variables.c

the green text explains what the functions do.

I would reccomend creating a linked list of "variables" if you want to be able to add variables
Or if the dictionary is fixed i would use an array of structs

set_variable() will search the array and change the value
variable_vaule() will search the array and return the value
display_variables() will printf() al the variables

dictionary_test.c is the main function (hence it contains main()) this is the one you run

Sounds like you have had this project before. Is that correct?

your variables.c file should NOT have a "main()" function. your variables.c file should have ONLY the implementation of the three functions prototyped in variables.h.

the two files, variables.c and variables.h are a pair. the .h declares the prototypes, the .c defines the implementation. you may not be used to seeing .h files, they are not strictly necessary. but you will find they are increasingly important as your projects get bigger and more files are involved.

the "dictionary_test" file is the file that has the "main()" routine. this is the entry point when the program is executed. this file will have the "#include variables.h" which links the functions compiled from the "variables.c" that you will write, so that those functions can be used in the program.

your job now is to write these three functions, put them in the "variables.c" file, …

COKEDUDE 27 Junior Poster in Training

I have 3 files. variables.h, variables.c, and dictionary_test.c. How would I use my variables.c to get information from variables.h and dictionary_test.c? I'm not supposed to touch the variables.h and dictionary_test.c. I gotta do all the work in variables.c. This is the variables.h.

#define MAX_VARIABLE_LENGTH 15

/* Set the variable with the specified name to the specified value.
 * If there is not a variable with that name in the dictionary,
 * add one. */
void set_variable (const char* name, double value);


/* Return the value of the variable with the specified name.
 * If variable does not exist, add it to the dictionary
 * with a default value of 0.0, and return that value. */
double variable_value(const char* name);


/* Display the names and values of all variables in the dictionary. */
void display_variables();

This is the dictionary_test.c.

#include <stdio.h>
#include "variables.h"

void verify (double result, double expected_value)
{
    if (result != expected_value)
    {
        printf ("Incorrect result.  Should be %8.4f\n\n", expected_value);
    }
}

int main()
{
    double result;

    printf ("Starting dictionary test\n\n");
    set_variable("A1", 1.0);
    set_variable("A2", 2.0);
    set_variable("A3_3333", 3.3333);

    result = variable_value("A1");
    printf ("A1 is %8.4f.\n", result);
    verify(result, 1.0);

    result = variable_value("A2");
    printf ("A2 is %8.4f.\n", result);
    verify(result, 2.0);

    result = variable_value("A3_3333");

    printf ("A3_333 is %8.4f\n", result);
    verify(result, 3.3333);

    set_variable("A long variable", -1.0);
    result = variable_value("A long variable");
    printf ("A long variable is %8.4f\n", result);
    verify(result, -1.0);

    result = variable_value("Unset Variable ");
    printf ("Unset Variable  is %8.4f\n", result);
    verify(result, 0.0);

    printf ("\n");
    printf ("All variables:\n");
    display_variables();

    printf ("Dictionary test …
COKEDUDE 27 Junior Poster in Training

Can someone please explain why "#include <stdlib.h>" fixes "warning: implicit declaration of function". Also what does #include <stdlib.h> mean and when should you use it?

COKEDUDE 27 Junior Poster in Training

these are warnings, not errors. meaning your program will compile and run (for a while), but probably will not work as expected because you're doing something unusual.

first one is you're assigning an int (length) to the char array (input_buffer).

before we can fix it, we've got to know what are you trying to do in the first place? are you trying to find the length of the string? then you need to use a function like "strlen()"

second one is just simply that you have a variable (cur_pos) that is not being used anywhere. the warning is in case you meant to use it but forgot. either delete it entirely or fix your code to use it.

another problem i see is the "return" statement in line 20. everything after that is meaningless because it will never get executed anyhow.

Wow thats just lovely on the "return" statement in line 20 part. My professor is the one that told me to put it there.

COKEDUDE 27 Junior Poster in Training

Could someone please tell me what these errors mean and how to fix them.

inputter.c: In function âget_next_tokenâ:
inputter.c:21: warning: initialization makes integer from pointer without a cast
inputter.c:17: warning: unused variable âcur_posâ
/* Get an RPN expression from the keyboard.
 * Accepts q as indictation that user wants to quit. 
 * Skips over invalid characters.
 * Normal end of expression is '='.  
 */

#include <stdio.h>
#include <ctype.h>
#include "inputter.h"

char *get_next_token(void)
{
    //return "123";
	int i = 0;
    char next_ch;
    static char input_buffer [1000] = {""};
    static int cur_pos = 0;
    printf ("Enter an RPN expression ending with =\n");
    fgets(input_buffer, 1000, stdin);
    return input_buffer;
	int length = input_buffer;
    //here
	do
    {
        next_ch = getchar();

        if (tolower((int)next_ch) == 'q')
        {
            // User wants to quit.
            input_buffer[0] = 'q';
            i++;
            break;
        }

        if ((next_ch == '\n') && (i > 0))
        {
            break;
        }

       if (isdigit(next_ch) ||
            (next_ch == '+') ||
            (next_ch == '-') ||
            (next_ch == '*') ||
            (next_ch == '/') ||
            (next_ch == '=')    )
        {
            input_buffer[i++] = next_ch;
        }

    } while ((input_buffer[i-1] != '=') && (i < length-1));
    //here
    input_buffer[i] = 0;     // Provide null terminator.

    while (next_ch != '\n')  // Clear keyboard input buffer
    {
        next_ch = getchar();
    }
}
/*
 * This function prompts the user to enter an RPN string
 * and reads the keyboard input into the buffer
 * specified by the caller.
 */

//void get_input(char* input_buffer, int length);

char *get_next_token(void);
COKEDUDE 27 Junior Poster in Training

Where does that swap function come from. I'm betting that neither ctype.h, string.h, nor stdio.h define a function which matches the method header that you attempted to use in your call to swap().

I thought the swap function was defined in #include <stdio.h>. Is that correct?

COKEDUDE 27 Junior Poster in Training

If you think that "\n" is a terminating null, it is not. "\0" is the terminating null. When you declare a char array, such as char mySchool[10] = "stuff" the compiler adds in the "\0" for you. So strlen starts at 0 for length and counts any character under it reaches \0. "\n" is the newline character which you can think of as the 'enter' button. For example when the user hits enter, it inserts a newline into the input buffer (of course it also inserts whatever text the user typed before they hit enter).

I didn't realize "\n" counts as one character so I couldn't figure out what was happening.

COKEDUDE 27 Junior Poster in Training

Can someone please explain why this function will not compile.

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

// This function determines if a string is a palindrome.
/* This function reverses the characters in the string
 * passed by the caller. */
void is_palindrome (char* string)
{
    int i;
    int length = strlen(string);
    int half_way = length/2;

    printf ("Function reverse called for string %s\n",
               string);

    for (i = 0; i < half_way; i++)
    {
        swap (&string[i], &string[length-1-i]);
    }
}

int main(void)
{
    char input[1000] = "";
    printf ("Enter a message: ");
    fgets(input, 1000, stdin);
    input[999] = 0;
 
    is_palindrome(input);

    return 0;
}
COKEDUDE 27 Junior Poster in Training

I'm going through my professors notes right now and he says in big bold print "Length does not include terminating null". I've looked at 2 different versions of this and in both cases it counts the terminating null. Can someone explain why this is happening.

Case 1

#include <stdio.h>
#include <string.h>
 
int main ()
{
    char mySchool[29] = "\n";
    printf (mySchool);

    printf ("Length of string mySchool is %d\n", strlen(mySchool));

    printf ("Size of string mySchool is %d\n", sizeof(mySchool));

    return 0;
}

Case 2

#include <stdio.h>
#include <string.h>
 
int main ()
{
    char mySchool[29] = "University of South Florida\n";
    printf (mySchool);

    printf ("Length of string mySchool is %d\n", strlen(mySchool));

    printf ("Size of string mySchool is %d\n", sizeof(mySchool));

    return 0;
}
COKEDUDE 27 Junior Poster in Training

Because it's a standard header.

Whats a standard header? I'm not familiar with that.

COKEDUDE 27 Junior Poster in Training

Here is a nice little swap function with a good explanation about what is going on.
http://computer.howstuffworks.com/c26.htm

COKEDUDE 27 Junior Poster in Training

Biggest difference is tolower() is a standard function and strlwr() is specific to certain compilers, non standard. tolower() converts 1 character. strlwr() converts a string

I thought since you need #include <ctype.h> for tolower() it is not standard. Why would you have to include #include <ctype.h> if it is a standard function?

COKEDUDE 27 Junior Poster in Training

Whats the difference between strlwr() and tolower()?

COKEDUDE 27 Junior Poster in Training

q: ? Sorry missed the arrows part the first time q colon does a little menu maybe you did that instead of :q

Correct :). Thx for figuring that out.

COKEDUDE 27 Junior Poster in Training

You can use a return from a void function.


Which loop do you see as nested?

In unix it gives you a warning. I'm not allowed to have warnings.

As for part 2.
The if loop is nested in the while loop.

COKEDUDE 27 Junior Poster in Training

I'm having difficulty breaking out of this nested loop. This is a function for reducing a fraction. Normally original_num and original_denom will be numbers that are reducible and z will normally be the GCD. Sometimes like in this particular that you see here 37 and 51 are not reducible. The only two ways I know of to break out of a loop is with a break statement or return 0, but in this case neither will work. I have a void statement so can't use a return statement and its a nested loop so I can't use a break statement.

void reduce(int original_num, int original_denom, int *reduced_num, int *reduced_denom)
{
    int z = 1;
    int a = 0;
    int b = 0;
    int original_num = 37;
    int original_denom = 51;
    //int i = 0;
    a = original_num;
    b = original_denom;
	
	//z = gcd(original_num , original_denom);
	printf("The value of z is %d\n", z);
    
    while(a / z != 0)
    {
        if((a / z) != 0)
        {
            a /= z;
		}
		else if(a / z == a)
		{
			break;
		}
    }
    while(b / z != 0)
	{
		if((b / z) != 0)
		{
			b /= z;
		}
        else if(b / z == b)
		{
		    break;
		}
    }

    *reduced_num = a;
    *reduced_denom = b;
}
COKEDUDE 27 Junior Poster in Training

The up and down arrow keys show you're last command

http://vim.wikia.com/wiki/Using_command-line_history

How do you get your recent vi command history to show up? I keep randomly getting like my previous 5 commands and can't figure out how I'm doing it. I think it has something to do with the shift key and another button. I know you can use the up and down arrows, but I know there's a way to see the recent commands.

I want the recent commands.

COKEDUDE 27 Junior Poster in Training

How do you get your recent vi command history to show up? I keep randomly getting like my previous 5 commands and can't figure out how I'm doing it. I think it has something to do with the shift key and another button. I know you can use the up and down arrows, but I know there's a way to see the recent commands.

COKEDUDE 27 Junior Poster in Training

Check out this link for more information... The problem being discussed here is pretty similar to yours

http://www.daniweb.com/forums/thread259931.html

Thats my own thread. I wasn't clearing my buffer with this below, and now I am.

while(getchar() != '\n');
COKEDUDE 27 Junior Poster in Training

I have a weird Buffer Clearing Error in this code. This is the line that is causing the error.

if(a<=0)

After you compile the code and run the code put in a group of letters like abc when the programs asks you to put in an integer. The first one or two times you run the code it produces some random massive number. After you run the code one or two times the code magically fixes itself. The code is supposed to ask you to enter another integer if you give a number less than 1 or any letters. The reason I know that line is causing the problem is, if I change the line above to this below then the program runs fine.

while(a<=0)

I'm using a unix system. Can anyone explain why this is happening and how the code magically fixes itself.

#include <stdio.h>
int gcd(int x, int y)
{
    if ( y == 0 )
    {    
        return x;
    }
    else if (x%y == 0)
    {
        return y;
    }
    else
    {
        return gcd(y,x%y);
    }
}

int get_input()
{
    int a, i=0;
    scanf("%d", &a);
    while(getchar() != '\n');
    if(a<=0) 
    { 
        for (i = 0; a <= 0; i++)
        {
            printf("Please enter an integer greater than 0\n");
            scanf("%d", &a);
            while(getchar() != '\n');
        }
    }
    return a;
}

int main()
{
    int x = -1;
    int y = -1;
    int z;
    printf("This program computes the greatest common divisor\n");
    printf("of positive integers x and y, entered by the user\n");
    printf("Inputs …
COKEDUDE 27 Junior Poster in Training

"C INPUT FUNCTIONS" brings up sites with help on input functions in C.

Wow. Adding the word programming completely confused the google search. I searched for "c programming input function" and I couldn't find anything helpful.

COKEDUDE 27 Junior Poster in Training

Does anyone know where there is any good documentation for input functions in C programming? I've been searching google for quite awhile with no luck :(.

COKEDUDE 27 Junior Poster in Training

scanf is a notoriously difficult function to use, especially for beginners.

try using fgets in conjunction with atoi instead.

char strInput[MAX_LEN_INPUT];
int value;

fgets(strInput, MAX_LEN_INPUT-1, stdin);
value = atoi(strInput);

once you figure out this basic method, use strtol instead of atoi, and you can make a pretty bulletproof input routine


.

How would I do that with my code that I have? What you showed me in that code is really confusing to me.

COKEDUDE 27 Junior Poster in Training

Thx both of you. What both of you said helps a lot :).

COKEDUDE 27 Junior Poster in Training

With my code below how would I either ignore or remove decimal numbers? I tried typecasting it but that messed up my code. I can't think of any way to make a loop to accept only integers either :(. I don't understand why the scanf is accepting decimal numbers when I am using %d and I declared my variables as ints. Any ideas would be greatly appreciated :).

#include <stdio.h>

int main (void)
{
    int x , y;
    int z;
    
    printf("Please enter a value for x:\n");

    printf("x: ");
    scanf("%d" , &x);
    //x = (int) x;
    while((x < 0) || (getchar() != '\n'))
    {
        printf("Please enter interger greater than 0\n");
        printf("Please enter a value for x:\n");
        printf("x: ");
        scanf("%d" , &x);
    }

    printf("Please enter a value for y:\n");
    printf("y: ");
    scanf("%d" , &y);
    //y = (int) y;
    while((y < 0) ||(getchar() != '\n'))
    {
        printf("Please enter interger greater than 0\n");
        printf("Please enter a value for y:\n");
        printf("y: ");
        scanf("%d" , &y);
    }

    return 0;
}
COKEDUDE 27 Junior Poster in Training

Do you know what a void function is? Do you know what it returns?

Not really. I was told by my teacher to use void but it looks like this is causing problems.

COKEDUDE 27 Junior Poster in Training

Could someone explain where and when you would use << and >>. I read these 2 articles but don't really understand them.
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
http://en.wikipedia.org/wiki/Arithmetic_shift

COKEDUDE 27 Junior Poster in Training

what are the error message(s) ?

lines 9 and 19: why did you stick those returns in the middle of those if statements? That makes line 10, 11, 20 and 21 unusable because they can never be executed.

Mising } between lines 12 and 13.

Here's the full code. I just didn't want to show it all since I know the main is really incomplete right now.

#include <stdio.h>

void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            x = y;
            y = c;
            return y;
        }
    }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            y = x;
            x = d;
            return x;
        }

    }
}

int main (void)
{
    printf("Please enter a value for x:\n");

    printf("x: ");
    scanf("%d" , &x);

    printf("Please enter a value for y:\n");

    printf("y: ");
    scanf("%d" , &y);

    printf("gcd of x and y  %d and %d\n", x, y);


    return 0;
}

I added the brace in between those 2 lines you said.

I didn't know those lines would become unusable. I fixed it.

I forgot to add the errors.
gcd.c: In function 'gcd':
gcd.c:13: warning: 'return' with a value, in function returning void
gcd.c:24: warning: 'return' with a value, in function returning void
gcd.c: In function 'main':
gcd.c:35: error: 'x' undeclared (first use in this function)
gcd.c:35: error: (Each undeclared identifier is reported only once
gcd.c:35: error: for …

COKEDUDE 27 Junior Poster in Training

Can someone tell me why my compiler won't compile this code and how to fix it?

void gcd(int x, int y)
{
    if (x > y)
    {
        int c;
        while(1)
        {
            c = x % y;
            return y;
            x = y;
            y = c;
        }
    if (y > x)
    {
        int d;
        while(1)
        {
            d = x % y;
            return x;
            y = x;
            x = d;
        }

    }
}
COKEDUDE 27 Junior Poster in Training

I'm trying to use the numbers to do calculations in my function. I want user input to get those 2 numbers.

COKEDUDE 27 Junior Poster in Training

When you have a function and need to scan for 2 different numbers, should the scanf be in the function or in the main() and why?

COKEDUDE 27 Junior Poster in Training

You did not answer Dave's question. Although we can surmise from your answer it's from main()

Could you please give me an example of returning from a function please?

COKEDUDE 27 Junior Poster in Training
while (getchar() != '\n')
    ;

This code will read a character from the keyboard buffer.
If the character is not '\n' do it again. Keep it up until '\n' is read.

The body of the loop is empty because all the work is done with the getchar() function.

Thx for explaining that :).

You don't know what "it does nothing" means?

Please, tell me what you think "it does nothing" could possibly mean.

I didn't understand how what you were saying was possible. I thought it would cause an infinite loop. I didn't know it would stop after it read " '\n' " like WaltP just explained.

COKEDUDE 27 Junior Poster in Training

Returning from a generic function, or returning from main? Returning from main means your program is "done".

A couple of while and for loops.

COKEDUDE 27 Junior Poster in Training

return x; will return the value x to the calling routine. If you called the function with rt = func(); rt will contain whatever x was. break; will immediately exit a loop even though the loop is not finished.

for (i=0; i<10; i++)
{
    --stuff--
    if (i == 7) break;
    --more stuff--
}

This loop will exit when i = 7. It won't run until i >= 10. And --more stuff-- will not be executed either.

When I put "return 1" in a few of my programs it stopped execution of the rest of my program.

You realy should google C functions and C control statements....You'll find the answers in these queries...

Nothing useful in relationship to my question. I checked the first 20 links with no luck.
http://www.google.com/search?q=c+programming+return+1&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
http://www.google.com/search?q=c+programming+return+statement&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

COKEDUDE 27 Junior Poster in Training

Read what I wrote, please. It's an empty statement as the loop body. It's an empty statement; it does nothing. It's in the loop body. The loop body repeatedly does nothing.

I did but I don't understand what that means :(.

COKEDUDE 27 Junior Poster in Training

Can someone please explain the meaning of these return 1 vs return 0 vs break. I know 1 generally means true and 0 generally means false but how would they effect a return statement? Also when would you wanna use a return statement instead of a break statement and vice versa?

COKEDUDE 27 Junior Poster in Training

It ain't random. It's an empty loop body. Putting it on a separate line helps people understand that it is intentional, rather than what can be a common bug (when people inadvertently create an empty loop body by placing an errant semicolon after a while or for statement).

So what does that ";" mean and what does it do? Sorry I'm new with c.

COKEDUDE 27 Junior Poster in Training

>How would I make all letters be an invalid input?
I notice you don't check the return value of scanf. That's the first step in recognizing whether it failed or not. Then you can recover:

while (scanf("%f", &purchase) != 1) {
  /* This is me being lazy */
  [B]while (getchar() != '\n')
    ;[/B]
  clearerr(stdin);
  printf("Invalid input, do it again: ");
  fflush(stdout);
}

I just noticed you put a random ";" after your while loop. Is that on purpose? I thought you didn't put ";" after a while loop.

COKEDUDE 27 Junior Poster in Training


>I still have to come across this error
Let me guess: you use Windows. I haven't encountered that issue on Windows either, but it's prevalent on Unix/Linux. In other words, it's a portability issue. I'm almost like a broken record when it comes to portability, ne?

I gotta use Unix/Linux so that would be a very big problem for me :(.

COKEDUDE 27 Junior Poster in Training

>Another solution could be something of this sort
If the user types letters, scanf will fail and leave i uninitialized. Accessing an uninitialized variable's value is undefined behavior. The suggestion becomes reasonable if you initialize to an invalid value for the program (like 0).

But then you've got the bigger problem of a dirty input stream in the case of letters. I hope you don't plan on taking any input after this, because there's no telling what you'll get. ;)

I discovered that after testing it out :). I was googling and reading my book for ideas with no luck. I was really annoyed after I figured that out :(. Won't using that while loop in your previous post also deal with clearing the input?

COKEDUDE 27 Junior Poster in Training

You need to read the input as characters
Test each character to make sure it's a digit
If so, convert the value to int/float.

How would I do that? I'm new with c.

COKEDUDE 27 Junior Poster in Training

How would I make all letters be an invalid input? I want all letters, numbers greater than 20, and numbers less than or equal to 0 to be invalid inputs. I used an or cause I want any case to be an invalid input. Any help would be greatly appreciated.

#include <stdio.h>
#include <math.h>

int main (void)
{
    float purchase = 0;


    printf("Please enter amount of purchase:\n");

    printf("purchase: ");
    scanf("%f" , &purchase);
    printf("The purchase you entered is: $%.2f\n", purchase);

    if((purchase  > 20) || (purchase <= 0))
        {
        printf("Invalid purchase amount\n");
        printf("Amount should be greater than 0 and less than or"); 
        printf(" equal to 20\n");
        return 1;
        }



    return 0;
}
COKEDUDE 27 Junior Poster in Training

Try googling C format specifiers..

Sorry I didn't know what the official terminology is of what I was looking for.

COKEDUDE 27 Junior Poster in Training

Can you please give me a list of all of the % letters that go with int, floats, and doubles in printf and scanf.

COKEDUDE 27 Junior Poster in Training

I don't understand what to do to fix the problem :(.