Converting string to float

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DirtyRasa
    New Member
    • Nov 2007
    • 4

    Converting string to float

    Here is what my professor told me to to.

    Write a function that converts a string to a float and returns a float.
    Test your function by entering f4 and with 4f. Both should say
    Data entered was not a number. Try again.
    and ask the user to type in another number.

    Here's what I have so far.

    Code:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define MAX_SIZE 80
    
    void readString(char prompt[], char str[]);// Exercise 1
    float readNumber(char prompt[], char str[]);// Exercise 2
    
    int main()
    {
    	char str[MAX_SIZE];
            printf("You entered: %f\n", readNumber("Please enter a number: ", str));
    }
    
    void readString(char prompt[], char str[]) //This asks the user for a string
    {
    	printf("%s", prompt);
    	gets(str);
    }//Exercise 1
    
    float readNumber(char prompt[], char str[]) //This function will convert the string   in to a float using readString
    {
    	int flag = 0; //0 means no; 1 means yes
    	int i;
    	float number;
    
    	readString(prompt, str);
    	sscanf(str, "%f", &number);
    
    	if(number == 0)
    	{
    		while(flag == 0)
    		{
    			printf("Data entered was not a number, Try again.\n");
    			readString(prompt, str);
    			sscanf(str, "%f", &number);
    			if(number != 0)
    				flag = 1;
    		}
    	}
    	return number;
    }//Exercise 2
    My problem is using sscanf. I'm not exactly sure how to use it so that it will only return a number if and only if the user enters a number. I'm guessing my if statements are incorrect as well, but I don't know how to use sscanf at all so I don't know how to check if the string only contains floats.
  • Shashi Sadasivan
    Recognized Expert Top Contributor
    • Aug 2007
    • 1435

    #2
    is the code returning any problems?
    what you also need to consider is if the user enters 0 (zero) as input.
    In that case your code will tell that the user did not enter a number.

    Have a look at the return type of sscanf, your code of
    Code:
    if(number == 0)
    will throw errors if the string entered by the user is not a number

    Comment

    • DirtyRasa
      New Member
      • Nov 2007
      • 4

      #3
      No, its just that when I enter 4F it will return 4.000000. I want it to return: "Data entered was not a number. Try again."

      So, somehow I need it to use the sscanf function and make sure that when it converts the string to a float that the string ONLY contains numbers and if it doesn't it will ask the user to enter a new value for the string until the user enters ONLY numbers including floats.
      So if I enter 4.0 it will return 4.00000
      or if I enter -2 it will return -2.0000
      but if I enter 4f it should return "Data entered was not a number. Try again." and prompt me for another number.

      Hopefully you understand and can help me.
      I'm guessing my problem lies in the if statement. I have no idea on how to check if the string is made up of ONLY numbers.

      EDIT
      I changed my code around a bit
      Code:
      float readNumber(char prompt[], char str[])
      {
      	int flag = 0; //0 means no; 1 means yes
      	int i;
      	float number;
      
      	readString(prompt, str);
      	i = sscanf(str, "%f", &number);
      
      	if(i != 1)
      	{
      		while(flag == 0)
      		{
      			printf("Data entered was not a number, Try again.\n");
      			readString(prompt, str);
      			i = sscanf(str, "%f", &number);
      			if(i == 1)
      				flag = 1;
      		}
      	}
      	return number;
      }//Exercise 2
      I just changed the if statements. Now if the user enters 0 it will work. and if the user enters a character first than it will ask the user for another number. but if i have a character after the number it will just print out the number which should NOT happen.

      Comment

      • mattmao
        New Member
        • Aug 2007
        • 121

        #4
        Originally posted by DirtyRasa
        I'm guessing my problem lies in the if statement. I have no idea on how to check if the string is made up of ONLY numbers.
        Hi.

        There is a potentially useful function in the ctype.h lib for your consideration:

        Function: int isdigit (int c)
        Returns true if c is a decimal digit (`0' through `9').

        If you take the user input as a string, then you can use a loop to check each character to validate it.

        Also you can use another function: strtol


        BTW I took a look at your code, it is made up of exercise fragments, which is not a good idea. For keeping the top-down design, you should think the case to handle as a whole, then divide and conquer. The variable parameters in each of your functions don't make any sense up to now.

        My suggestion is: try to finish the input validation part first, then think further...

        Comment

        • DirtyRasa
          New Member
          • Nov 2007
          • 4

          #5
          Originally posted by mattmao
          Hi.

          There is a potentially useful function in the ctype.h lib for your consideration:

          Function: int isdigit (int c)
          Returns true if c is a decimal digit (`0' through `9').

          If you take the user input as a string, then you can use a loop to check each character to validate it.

          Also you can use another function: strtol
          http://www.gnu.org/software/libc/man...-Integers.html
          Is there a way to do this using only the sscanf function? I think my prof would get mad if I did it any other way.
          He didn't really tell us what we could or could not do though so I don't know. It's just when I started to use atof() he yelled at me so I don't know. So if there is a way to do this with sscanf mainly then any pointers in the right direction would be a great help. For now I'll just use isdigit.

          Comment

          • mattmao
            New Member
            • Aug 2007
            • 121

            #6
            Originally posted by DirtyRasa
            Is there a way to do this using only the sscanf function? I think my prof would get mad if I did it any other way.
            He didn't really tell us what we could or could not do though so I don't know. It's just when I started to use atof() he yelled at me so I don't know. So if there is a way to do this with sscanf mainly then any pointers in the right direction would be a great help. For now I'll just use isdigit.
            Emmm, that is pretty strange.

            This is not a research at all, google the references online shouldn't be blamed for...

            This is some references regarding sscanf, I am looking at it:






            Yeah, you can use the return value of sscanf to check if input is valid or not.

            if(sscanf (input, "%f", &number))
            {
            //do what ever you want to for the valid input.
            }
            else
            {
            //ask to give a new input.
            }


            BTW, the gcc compiler warns me that:
            Code:
            bash-3.2$ gcc test.c
            /tmp/ccqdvPdm.o: In function `takeInput':
            test.c:(.text+0x42): warning: the `gets' function is dangerous and should not be used.

            Comment

            • DirtyRasa
              New Member
              • Nov 2007
              • 4

              #7
              I still get it where if I enter 4f it returns 4
              Code:
              float readNumber(char prompt[], char str[])
              {
              	int flag = 0; //0 means no; 1 means yes
              	float number;
              
              	readString(prompt, str);
              
              	if(sscanf (str, "%f", &number))
              		return number;
              	else
              	{
              		while(flag == 0)
              		{
              			printf("Data entered was not a number, Try again.\n");
              			readString(prompt, str);
              			if(sscanf(str, "%f", &number))
              				{
              					flag = 1;
              					return number;
              				}
              		}
              	}
              
              }//Exercise 2
              I'm not sure what the if statement should be checking for... Thanks for your help though.

              Comment

              • mattmao
                New Member
                • Aug 2007
                • 121

                #8
                Originally posted by DirtyRasa
                I still get it where if I enter 4f it returns 4
                Code:
                float readNumber(char prompt[], char str[])
                {
                	int flag = 0; //0 means no; 1 means yes
                	float number;
                
                	readString(prompt, str);
                
                	if(sscanf (str, "%f", &number))
                		return number;
                	else
                	{
                		while(flag == 0)
                		{
                			printf("Data entered was not a number, Try again.\n");
                			readString(prompt, str);
                			if(sscanf(str, "%f", &number))
                				{
                					flag = 1;
                					return number;
                				}
                		}
                	}
                
                }//Exercise 2
                I'm not sure what the if statement should be checking for... Thanks for your help though.
                Hi.

                Use this:

                Code:
                float num;
                    char *temp;
                    if(sscanf(str, "%f%*s", &num, temp))
                This can solve that particular problem.

                Comment

                Working...