vendredi 13 mars 2015

atof( ) returning garbage; already included stdlib.h


In a program, I am converting a string read from stdin to a float. However, atof() returns garbage(3.217777*10e-39), which I saw in the watch list when debugging.


Code:



char name[MAXNAME];
float a;
cout << "What is the name? (press 'b' to go back to the menu)\n";
fgets(name, sizeof name, stdin);
replaceTrailingNl(name);

if (strcmp(name, "b") == 0 || strcmp(name, "B") == 0) {
menu();
return;
}

// problematic part ...
char *abuf = new(std::nothrow) char [MAXLINE];
do {
cout << "What is the amt?\n";
fgets(abuf, sizeof abuf, stdin);
replaceTrailingNl(abuf); //replaces trailing newline with \0

convertDollarToSpace(abuf); // initial '$' is replaced by space
} while (atof(abuf) == 0);
delete abuf;


I also tried using sscanf( ), but I also got garbage


Many answers on the Internet say to include <stdlib.h>. But I've already done so. Here is the top of the file, if that helps:



#include <iostream>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <cerrno>
#include <cctype>
#include "xaction.h" // a header containing a class



Aucun commentaire:

Enregistrer un commentaire