read flot value
how to read float valu from file like getw function used to read integer data. help plz. thanx
man getw wrote: |
---|
reads a word (that is, an int) from stream. It's provided for compatibility with SVr4. We recommend you use fread(3) instead. |
in C:
1 2 3 4 5 6
|
fscanf(FILE *object, "%f", &float_variable);
fgets(buffer, sizeof buffer, FILE *object);
sscanf(buffer, "%f", &float_variable);
scanf("%f", &float_variable);
|
in C++:
1 2 3 4 5 6 7
|
fstream_obj >> float_variable;
getline(cin, string_obj);
istringstream iss(string_obj);
iss >> float_variable
cin >> float_variable;
|
Or you can even whip up your own since c++ provides you with that option\
C++11:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// Something I used in one of AI projects
class scanFields
{
template<typename F>
bool get(F &first) {
return (cin >> first).good();
}
template<typename F, typename... T>
bool get(F &first, T&... values) {
return (cin >> first).good() && get(values...);
}
public:
template <typename... T>
scanFields(const string message, T&... values) {
while (cout << message && !get(values...)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
};
|
Usage:
1 2 3 4 5 6 7
|
int main()
{
float f;
scanFields("Enter a float: ", f);
cout << "You entered " << f << endl;
return 0;
}
|
Last edited on
Topic archived. No new replies allowed.