C++ - Read from file to double [closed]

。_饼干妹妹 提交于 2019-12-30 23:50:02

问题


I'm relatively new to programming and taking a course in C++ currently. I haven't had any major problems so far. I am making a program where an X amount judges can score 0.0 - 10.0 (double) and then the highest and lowest one is removed then an average is calculated and printed out.

This part is done, now I want to read from a file in the shape of: example.txt - 10.0 9.5 6.4 3.4 7.5

But I am stumbling onto problems with the dot (.) and how to get around it to get the number into a double. Any suggestions and (good) explanations so I can understand it?


TL;DR: Reading from file (E.G. '9.7') to a double variable to put into an array.


回答1:


Since your textfile is whitespace delimited, you can use that to your advantage by utilizing std::istream objects who skip whitespace by default (in this case, std::fstream):

#include <fstream>
#include <vector>
#include <cstdlib>
#include <iostream>

int main() {
    std::ifstream ifile("example.txt", std::ios::in);
    std::vector<double> scores;

    //check to see that the file was opened correctly:
    if (!ifile.is_open()) {
        std::cerr << "There was a problem opening the input file!\n";
        exit(1);//exit or do additional error checking
    }

    double num = 0.0;
    //keep storing values from the text file so long as data exists:
    while (ifile >> num) {
        scores.push_back(num);
    }

    //verify that the scores were stored correctly:
    for (int i = 0; i < scores.size(); ++i) {
        std::cout << scores[i] << std::endl;
    }

    return 0;
}

Note:

It is highly recommended to use vectors in lieu of dynamic arrays where possible for a myriad number of reasons as discussed here:

When to use vectors and when to use arrays in C++?




回答2:


Try this:

#include <iostream>
#include <fstream>

int main() 
{
    std::ifstream fin("num.txt");
    double d;
    fin >> d;
    std::cout << d << std::endl;
}

Does that do what you want?



来源:https://stackoverflow.com/questions/19885876/c-read-from-file-to-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!