473,672 Members | 2,641 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting string to float

4 New Member
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:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. #define MAX_SIZE 80
  6.  
  7. void readString(char prompt[], char str[]);// Exercise 1
  8. float readNumber(char prompt[], char str[]);// Exercise 2
  9.  
  10. int main()
  11. {
  12.     char str[MAX_SIZE];
  13.         printf("You entered: %f\n", readNumber("Please enter a number: ", str));
  14. }
  15.  
  16. void readString(char prompt[], char str[]) //This asks the user for a string
  17. {
  18.     printf("%s", prompt);
  19.     gets(str);
  20. }//Exercise 1
  21.  
  22. float readNumber(char prompt[], char str[]) //This function will convert the string   in to a float using readString
  23. {
  24.     int flag = 0; //0 means no; 1 means yes
  25.     int i;
  26.     float number;
  27.  
  28.     readString(prompt, str);
  29.     sscanf(str, "%f", &number);
  30.  
  31.     if(number == 0)
  32.     {
  33.         while(flag == 0)
  34.         {
  35.             printf("Data entered was not a number, Try again.\n");
  36.             readString(prompt, str);
  37.             sscanf(str, "%f", &number);
  38.             if(number != 0)
  39.                 flag = 1;
  40.         }
  41.     }
  42.     return number;
  43. }//Exercise 2
  44.  
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.
Nov 21 '07 #1
7 4466
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
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
Expand|Select|Wrap|Line Numbers
  1. if(number == 0)
will throw errors if the string entered by the user is not a number
Nov 21 '07 #2
DirtyRasa
4 New Member
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
Expand|Select|Wrap|Line Numbers
  1. float readNumber(char prompt[], char str[])
  2. {
  3.     int flag = 0; //0 means no; 1 means yes
  4.     int i;
  5.     float number;
  6.  
  7.     readString(prompt, str);
  8.     i = sscanf(str, "%f", &number);
  9.  
  10.     if(i != 1)
  11.     {
  12.         while(flag == 0)
  13.         {
  14.             printf("Data entered was not a number, Try again.\n");
  15.             readString(prompt, str);
  16.             i = sscanf(str, "%f", &number);
  17.             if(i == 1)
  18.                 flag = 1;
  19.         }
  20.     }
  21.     return number;
  22. }//Exercise 2
  23.  
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.
Nov 21 '07 #3
mattmao
121 New Member
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
http://www.gnu.org/software/libc/man...-Integers.html

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...
Nov 21 '07 #4
DirtyRasa
4 New Member
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.
Nov 21 '07 #5
mattmao
121 New Member
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:
http://www.crasseux.com/books/ctutorial/sscanf.html
http://www.cplusplus.com/reference/c...io/sscanf.html




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:
Expand|Select|Wrap|Line Numbers
  1. bash-3.2$ gcc test.c
  2. /tmp/ccqdvPdm.o: In function `takeInput':
  3. test.c:(.text+0x42): warning: the `gets' function is dangerous and should not be used.
Nov 21 '07 #6
DirtyRasa
4 New Member
I still get it where if I enter 4f it returns 4
Expand|Select|Wrap|Line Numbers
  1. float readNumber(char prompt[], char str[])
  2. {
  3.     int flag = 0; //0 means no; 1 means yes
  4.     float number;
  5.  
  6.     readString(prompt, str);
  7.  
  8.     if(sscanf (str, "%f", &number))
  9.         return number;
  10.     else
  11.     {
  12.         while(flag == 0)
  13.         {
  14.             printf("Data entered was not a number, Try again.\n");
  15.             readString(prompt, str);
  16.             if(sscanf(str, "%f", &number))
  17.                 {
  18.                     flag = 1;
  19.                     return number;
  20.                 }
  21.         }
  22.     }
  23.  
  24. }//Exercise 2
  25.  
I'm not sure what the if statement should be checking for... Thanks for your help though.
Nov 21 '07 #7
mattmao
121 New Member
I still get it where if I enter 4f it returns 4
Expand|Select|Wrap|Line Numbers
  1. float readNumber(char prompt[], char str[])
  2. {
  3.     int flag = 0; //0 means no; 1 means yes
  4.     float number;
  5.  
  6.     readString(prompt, str);
  7.  
  8.     if(sscanf (str, "%f", &number))
  9.         return number;
  10.     else
  11.     {
  12.         while(flag == 0)
  13.         {
  14.             printf("Data entered was not a number, Try again.\n");
  15.             readString(prompt, str);
  16.             if(sscanf(str, "%f", &number))
  17.                 {
  18.                     flag = 1;
  19.                     return number;
  20.                 }
  21.         }
  22.     }
  23.  
  24. }//Exercise 2
  25.  
I'm not sure what the if statement should be checking for... Thanks for your help though.
Hi.

Use this:

Expand|Select|Wrap|Line Numbers
  1. float num;
  2.     char *temp;
  3.     if(sscanf(str, "%f%*s", &num, temp))
This can solve that particular problem.
Nov 21 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

15
4616
by: Bushido Hacks | last post by:
Hey c.l.c++ and/or c.g.a.opengl posters, How do I convert a hexidecimal string, traditionally used for defining colors with HTML, into a floating point array? In other words, how do I convert this: char* hex = "#FF9933"; into this:
1
1867
by: Meya-awe | last post by:
Hello there, I am using a 3rd party library and a function which requires a float value in one of its methods. My data is in a string format and i tried using Convert.ToDouble and Convert.ToSingle, but didn't work either way. The value of string is "-57475.4531". The help in VS .NET 2003 tells me that these convert methods will return double and single precision float point values respectively but i needed to also cast the return to the...
5
7867
by: vivekaseeja | last post by:
Hi , Trying to convert a string value to a float value after reading the value from an XML file , but not sure what function to use. The following only works for integers Int32.Parse (readXml.Value) ; Any suggestions for an alternate function ..
3
1838
by: Jim Langston | last post by:
I have a CSkill class which is rather complex as it is recursive. That is: class CSkill { public: CSkill( std::string Name, float Value ): Name_( Name ), Value_( Value ) {}; void Update( const std::string& Name, const float Value ); float Value( const std::string& Name ) const; float Sum( const std::string& Name ) const;
3
41234
by: pipe.jack | last post by:
I'm trying to convert string to float and my float after conversion is 0 (zero). Here is my code: $c = $currencies->format($cart->show_total()); echo gettype($c); echo (float)$c; $c = 39.59 gettype($c) = string echo (float)$c; = 0
3
3249
by: psbasha | last post by:
Hi , When ever we read any data from file ,we read as a single line string ,and we convert the respective field data available in that string based on the data type ( say int,float ). Please suggest me which is the best way of handling the file data. I- Method: ---------------- Store as single line string data's(upto end of file ) in a list and make use of this string list for the entire application.
12
11278
by: joestevens232 | last post by:
Okay, Im having some problems with my code. Im trying to use the <cstdlib> library and im trying to convert string data at each whitespace slot. I think if you see my code you'll get what im trying to do : #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; using std::ifstream; using std::ofstream;
10
3236
by: Hank Stalica | last post by:
I'm having this weird problem where my code does the following conversion from string to float: 27000000.0 -27000000.00 2973999.99 -29740000.00 2989999.13 -2989999.25 The number on the left is the string I get after tokenizing a bigger string. The number on the right is the number I get after the conversion.
7
4779
by: ma740988 | last post by:
Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single precision floating point types. The number of decimal digits guaranteed to be correct on my implementation is 6. (i.e numeric_limits < float >::digits10 = 6 ) If I'm reading the IEEE standard, I'd could paraphrase the issue
0
8488
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8932
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8685
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7449
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6240
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5709
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4230
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4421
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2821
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.