如何撰寫讀取輸入字串并將字串轉換為浮點數的程式。
我對這個功能有點困惑:
#include <stdlib.h>
#include <string.h>
double convert_to_double (char *);
int main(void)
{
char *s;
s = malloc(10 * sizeof(char));
printf("Enter text: ");
fgets(str, 10, stdin);
printf("The number is %lf", convert_to_double (str));
return 0;
}
double convert_to_double (char *str) {
double convert_to_double (char *str) {
char *s;
double result;
result = strtod(str, &s);
if (s != NULL) {
char *anotherEnd;
double anotherResult = strtod(s, &anotherEnd);
}
if (isalnum(s) == 0){
printf("Wrong digit entered..");
}
return result;
}
uj5u.com熱心網友回復:
如果要嚴格驗證輸入字串,請嘗試:
double convert_to_double(char *str)
{
char *e;
double d = strtod(str, &e);
if (*e != '\n') {
fprintf(stderr, "input error %c\n", *e);
exit(1);
}
return d;
}
字符*e為有效數字表示轉換后剩余的第一個字符;在這種用法中通常是換行符。如果您不必如此嚴格地檢查輸入字串,只需說:
double convert_to_double(char *str)
{
double d = strtod(str, (char **)NULL);
return d;
}
您可能不必對其進行操作。
uj5u.com熱心網友回復:
您對 strtod 的處理方式錯誤:
double convert_to_double (char *str) {
{
char *s;
double result;
// first parameter is the string you want to convert
// second pram is a pointer to the first char which was not converted.
// this can be used if you have more than one data to convert in the same string
result = strtod(str, &s);
// example of using returned pointer :
if (s != NULL) {
char *anotherEnd;
double anotherResult = strtod(s, &anotherEnd);
}
return result;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379844.html
上一篇:為什么即使代碼中沒有錯誤,我的代碼也沒有給出任何輸出?
下一篇:抽象出init函式的最佳方法?
