Thread: A basic math programming question

  1. #16
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The BEST version to convert a string to float is strtof() - it returns a float, but also tells you if it went OK or not.


    http://www.hmug.org/man/3/strtod.php

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  2. #17
    Registered User
    Join Date
    Feb 2008
    Posts
    84
    Prelude,
    I see your point. I do want to avoid such inputs. In fact, in my first incarnation I had exactly that problem:
    when using atoi instead of atof,
    if I input 3.2
    it would perform the division on just the 3.

    on the other hand, im finding the faq about fgets a bit confusing.
    could someone provide me with an example in the context of this program?

    thanks to everyone here for their help, as is very obvious, im just getting started...

  3. #18
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by hebali View Post
    Prelude,
    I see your point. I do want to avoid such inputs. In fact, in my first incarnation I had exactly that problem:
    when using atoi instead of atof,
    if I input 3.2
    it would perform the division on just the 3.

    on the other hand, im finding the faq about fgets a bit confusing.
    could someone provide me with an example in the context of this program?

    thanks to everyone here for their help, as is very obvious, im just getting started...
    The FAQ is an example in the context of your program.

    Code:
    char inXreal[8];
    
    fgets(inXreal, 8, stdin); // first 8 characters of input are now here

  4. #19
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    True, no argument with that. Just add error checking.

  5. #20
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Atoi converts a string to an integer (no decimals, in other words).
    Best use strtof or strtod.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #21
    Registered User
    Join Date
    Feb 2008
    Posts
    84
    aha! thanks. i get it now. sorry.

  7. #22
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >could someone provide me with an example in the context of this program?
    Sure:
    Code:
    #include <errno.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      char buffer[BUFSIZ];
    
      printf ( "Enter a floating-point number: " );
      fflush ( stdout );
    
      if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
        char *end;
        double x;
    
        errno = 0;
        x = strtod ( buffer, &end );
    
        if ( errno == ERANGE || end == buffer )
          fputs ( "Invalid input\n", stderr );
        else
          printf ( "You entered &#37;f\n", x );
      }
    
      return 0;
    }
    >Best use strtof or strtod.
    Note that strtof is only available in C99 or as an extension.
    My best code is written with the delete key.

  8. #23
    Registered User
    Join Date
    Feb 2008
    Posts
    84
    Slinger: by error checking do you mean "if ((p = strchr(buf, '\n')) != NULL)
    *p = '\0';"
    (as cited in the FAQ)?

    Elysia, from the hmug site, I see the following about the use of srttof:

    "strtof(const char *restrict nptr, char **restrict endptr);"
    but I am not sure what the implementations of those: const char *restrict nptr, etc are

  9. #24
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Is there a strtof actually? I can only see strotod.
    But as for the question, the usage goes like this:
    strotod(string_you_want_to_convert_here, [1]);
    [1] This is a pointer to a pointer (char**) that recieves the address where strtod stopped parsing the string. So if you add junk "10d", it will assign to a pointer to address in the string where "d" resides, so you know that at this point, it stopped parsing.

    You can just pass NULL if that was confusing.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #25
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but I am not sure what the implementations of those: const char *restrict nptr, etc are
    Don't worry about restrict for now. A lot of experienced C-ites have trouble with the concept, and it's still a very new feature. But to answer your question, the first parameter is the string with your value. The second parameter tells you how far into the string strtof got before it couldn't go on (you can pass NULL to this parameter if you don't care). For example:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ( void )
    {
      const char *p = "123.456test";
      char *end;
      double x;
    
      printf ( "Converting \"&#37;s\"\n", p );
      x = strtod ( p, &end );
      printf ( "Found %f with \"%s\" left over\n", x, end );
    
      return 0;
    }
    >Is there a strtof actually?
    In C99 or as an extension, yes. But prior to C99 you can't rely on it being supported.
    My best code is written with the delete key.

  11. #26
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    Quote Originally Posted by hebali View Post
    Slinger: by error checking do you mean "if ((p = strchr(buf, '\n')) != NULL)
    *p = '\0';"
    (as cited in the FAQ)?

    Elysia, from the hmug site, I see the following about the use of srttof:

    "strtof(const char *restrict nptr, char **restrict endptr);"
    but I am not sure what the implementations of those: const char *restrict nptr, etc are

    Was not thinking specifics but, scanf does have its limits with user input. If you are needing to check that a number, ie a float, was truly entered then you will need to check that no letters were entered, perhaps by checking against, isalpha? But Preludes recommendations looks good and clean.

  12. #27
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Problem is that it leaves crap in the input buffer which you need to clean (if it fails). That's why I like the fgets/strtod/strtol approach instead.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #28
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >That's why I like the fgets/strtod/strtol approach instead.
    This has the same problem, though it's subtler. In practice, fgets is best used as the foundation of a more robust, but application-specific, line reading function.
    My best code is written with the delete key.

  14. #29
    Registered User
    Join Date
    Feb 2008
    Posts
    84
    Ok, so my current implementation looks like this:
    Code:
    /* Variables */
    	float Xreal; 
    	float Yreal; 
    	float Zreal;
    	float Xforce;
    	float Yforce;
    	float Zforce;
    	float Tval;
    	char inXreal[8];
    	char inYreal[8];
    	char inZreal[8];
    	char inZforce[8];
    
    	
    /* Prompts */
    	
    	/* Get coordinates of real-perspective point */
    	printf("Xreal value: ");
    	fgets(inXreal, 8, stdin);
    	Xreal=strtof(inXreal, NULL);
    	
    	printf("Yreal value: ");
    	fgets(inYreal, 8, stdin);
    	Yreal=strtof(inYreal, NULL);
    	
    	printf("Zreal value: ");
    	fgets(inZreal, 8, stdin);
    	Zreal=strtof(inZreal, NULL);
    	
    	/* Get Z coordinate of forced-perspective point */
    	printf("Zforce value: ");
    	fgets(inZforce, 8, stdin);
    	Zforce=strtof(inZforce, NULL);
    
    /* Computation */
    	Tval=Zforce/Zreal;
    	Xforce=Tval*Xreal;
    	Yforce=Tval*Yreal;
    	
    /* Output Display */
    	printf("The point: (&#37;.3f, %.3f, %.3f) was generated with a Tvalue of: %.3f.\n",Xforce,Yforce,Zforce,Tval);
    	
    	return(0);
    }
    It builds. But, I think I may be seeing the effect of using NULL?? I'm not sure. When I run it, if each of the user input are the same length: for example, 2.343 5.425, etc., then it will perform normally. however, if i make one of the inputs have a different number of characters (length?) from the previous, it will skip the next prompt, and go right to the final output with incorrect values.

    What is this about?

    Thanks. I must say, this is the most helpful forum I've ever used. I'm new to programming, but not new to computing (mainly Maya, etc.) and you have all been wonderful.

  15. #30
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Everything has its ups and downs, but it's easier to check for errors and no need with annoying syntax to clear input buffers. IMHO, of course.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. handling basic math functions
    By MyDestiny in forum C++ Programming
    Replies: 3
    Last Post: 03-02-2005, 01:12 PM
  2. basic question to Arrays
    By doneirik in forum C++ Programming
    Replies: 1
    Last Post: 01-25-2005, 02:57 AM
  3. Basic Math Problem. Undefined Math Functions
    By gsoft in forum C Programming
    Replies: 1
    Last Post: 12-28-2004, 03:14 AM
  4. a simple math question
    By chunlee in forum C Programming
    Replies: 3
    Last Post: 11-10-2004, 07:04 AM