[英]C converting string/char input to floating point
I'm writing a program in C, and one of the requirements is that the user input a number as a string value, and then the program must convert it to floating point format, and then do various things to that value. 我正在用C编写程序,其中一项要求是用户输入数字作为字符串值,然后程序必须将其转换为浮点格式,然后对该值进行各种处理。 I can't seem to figure out how to simply convert the input string into a number. 我似乎无法弄清楚如何将输入字符串简单地转换为数字。 How would I write the first chunk of code like that? 我该如何编写第一段代码? I know there are posts similar to this, but they haven't been helpful. 我知道有类似的帖子,但是它们并没有帮助。 I need to do this fairly simply, and I'd like to not have to #include anything besides ... 我需要做的很简单,除了...之外,我不想#include任何东西。
#include <stdio.h>
int main(int argc,char* argv[]) {
/*having issues with this in particular...*/
int number;
int newNumber;
int i;
printf("Enter a number in decimal...");
scanf("%d",&number);
/* */
printf("%d in binary is: ",number);
for(i = 31;i >= 0;i--) {
newNumber = (number>>i);
if(newNumber & 1) {
printf("1");
}
else {
printf("0");
}
}
return 0;
}
Thanks! 谢谢!
You can use strtod()
. 您可以使用strtod()
。 Read the number into a buffer as a string (say with fgets()
), and then do: 将数字作为字符串读入缓冲区(例如,使用fgets()
),然后执行以下操作:
double x;
char *endptr;
errno = 0;
x = strtod(buffer, &endptr);
if (endptr == buffer) {
//... parse error or empty input ...
} else if (*endptr != '\n' && *endptr != '\0') {
//... parse error extraneous data ...
} else if ((x == HUGE_VAL || x == -HUGE_VAL) && errno != 0) {
//... error overflow ...
} else if (x <= DBL_MIN && x >= -DBL_MIN) {
if (errno != 0) {
//... error underflow (detected) ....
} else {
// ... underflow still possible, but is undiagnosed ...
}
}
Error checking is done by checking both the value returned for x
, and if errno
got set. 通过检查为x
返回的值以及是否errno
了errno
来进行错误检查。 Parse errors is done by checking the endptr
. 解析错误是通过检查endptr
来完成的。 The C standard says underflow detection is implementation defined (C.11 §7.22.1.3 ¶10). C标准说,下溢检测是实现定义的(C.11§7.22.1.3¶10)。
Following up on the comment I made: 跟进我的评论:
Your code appears to "work" - in that it reads the input and produces output. 您的代码似乎在“起作用”-因为它读取输入并产生输出。 You might consider adding
\\n
at the end of yourprintf
statements. 您可以考虑在printf
语句的末尾添加\\n
。 What exactly isn't working for you? 到底什么对您不起作用? Consider using8*sizeof(int)-1
rather than31
. 考虑使用8*sizeof(int)-1
而不是31
。 You don't know ahead of time how big an int is on your system. 您不会提前知道系统上的int大小。
With a tiny change your code works very nicely for me: 稍作更改,您的代码就可以很好地工作:
#include <stdio.h>
int main(int argc,char* argv[]) {
/*having issues with this in particular...*/
int number;
int newNumber;
int i;
printf("Enter a number in decimal...\n"); // <<< added a newline
scanf("%d",&number);
/* */
printf("%d in binary is: ",number);
for(i = sizeof(int)*8 - 1;i >= 0;i--) { // make sure `i` starts with the right size
newNumber = (number>>i);
if(newNumber & 1) {
printf("1");
}
else {
printf("0");
}
}
printf("\n"); // <<< print a newline
return 0;
}
When I run it: 当我运行它时:
Enter a number in decimal...
123
123 in binary is: 00000000000000000000000001111011
note - you do have to input an integer for this to work. 注意 -您必须输入一个整数才能起作用。 If you need your code to be more robust to user "error" in the input, your best bet is to read the input as a string, then do some more parsing. 如果您需要代码对输入中的用户“错误”更健壮,最好的选择是将输入作为字符串读取,然后再进行一些解析。 For example: 例如:
char buffer[100];
printf("enter an integer:\n");
fgets(buffer, 100, stdin);
// now you can look for spaces, letters, anything you want to skip, in the string
// you could even use sscanf().
// scanf() is a terribly fragile function to use, especially with "free form user input".
if(sscanf(buffer, "%d", &number) == 1) {
// successfully converted number... run your code
} else {
printf("unable to convert input to a number!\n%s\n", buffer);
return 0;
}
another note re-reading your question, you said "program has to convert to a floating point number. This means you should do 另一个说明重读了您的问题,您说“程序必须转换为浮点数 。这意味着您应该
float fnumber;
sscanf(buffer, "%f", &fnumber);
or 要么
double dnumber;
sscanf(buffer, "%lf", &dnumber);
to do the conversion. 进行转换。 But then, if you want to print as a binary, you need to cast the number from floating point to unsigned integer - a bit shifting operation is not well defined for a floating point number. 但是,如果要以二进制形式打印,则需要将数字从浮点数转换为无符号整数-浮点数的位移位操作定义不充分。 So 所以
unsigned int *intPtr, number;
intPtr = (unsigned int*) *fnumber; // this is hairy but it works
number = *intPtr;
and now use number
as before - you will be able to print out the binary equivalent of the floating point number. 现在像以前一样使用number
-您将可以打印出等效于浮点数的二进制代码。 There are people who will complain that the above is not "true to the standard". 有人会抱怨以上内容不是“符合标准”。 They might prefer it if you created a union: 如果您创建了工会,他们可能会更喜欢:
union f2i
{
float fvalue;
unsigned int ivalue;
} Values;
Then assign the input to Values.fvalue
, and use Values.ivalue
to print out the binary number. 然后将输入分配给Values.fvalue
,并使用Values.ivalue
打印出二进制数。 It is still a hack... 仍然是一个hack ...
Simple scanf example tested with GCC 4.7.3 用GCC 4.7.3测试的简单scanf示例
$ gcc -Wall -Wextra -pedantic -std=c99 cstring-double.c $ gcc -Wall -Wextra -pedantic -std = c99 cstring-double.c
#include <stdio.h>
int main() {
double v;
int err;
err = scanf("%lf", &v);
if (1 == err) {
printf("%lf\n", v);
} else {
printf("read failed\n"); }
return 0; }
Just use atof. 只需使用atof。 cplusplus documentation cplusplus文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.