[英]Converting gets() string into an integer in C
I am trying to write code that reads a string of numbers using gets()
and then converts said string into an integer. 我正在尝试编写使用gets()
读取一串数字的代码,然后将所述字符串转换为整数。 However something is going wrong with my conversion and I can't figure out what. 但是我的转换出了问题,我无法弄清楚是什么。 I also have to use gets()
to do this. 我还必须使用gets()
来执行此操作。 If anyone can see whats wrong or knows a better way to do this please help. 如果有人能看到什么错误或知道更好的方法,请帮助。
Thanks. 谢谢。
#include <stdio.h>
#include <math.h>
int main()
{
char s[1000];
int n = 0;
printf("Input the number you wish to have converted\n");//asks the user to enter the number they want converted
gets(s);//reads the input
for (int i = 0; i < length; i++)
{
char temp = s[i] - '0';
n = n + pow(10, length - i - 1) * temp;//converts from a character array to an integer for decimal to binary conversion
}
}
Instead of using your own method to do this, there are a number of utilities in the standard library. 标准库中有许多实用程序,而不是使用您自己的方法来执行此操作。 Take a look at strol
and sscanf
. 看看strol
和sscanf
。 It's also wise to use fgets
instead of gets
as pointed out in the comments above. 在上面的评论中指出使用fgets
代替gets
也是明智的。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[1000];
int n = 0;
printf("Input the number you wish to have converted\n");//asks the user to enter the number they want converted
fgets(s, sizeof(s), stdin);//reads the input
n = (int)strol(s, NULL, 10);
printf("Number from strol: %d\n", n);
sscanf(s, "%d", &n);
printf("Number from sscanf: %d\n", n);
}
You can even bypass fgets
and use scanf
if you don't want to keep the string: 如果您不想保留字符串,甚至可以绕过fgets
并使用scanf
:
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("Number from scanf: %d\n", n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.