C++ - 从文件读取双倍

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19885876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:13:32  来源:igfitidea点击:

C++ - Read from file to double

c++readfile

提问by Danieboy

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.

我目前对编程和学习 C++ 课程比较陌生。到目前为止,我还没有遇到任何重大问题。我正在制作一个程序,其中 X 数量的裁判可以得分 0.0 - 10.0(双倍),然后删除最高和最低的一个,然后计算并打印出平均值。

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

这部分完成了,现在我想从一个文件中读取: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.

TL;DR:从文件(EG '9.7')读取到一个双变量以放入一个数组。

回答by jrd1

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

由于您的文本文件是空格分隔的,因此您可以利用std::istream默认情况下跳过空格的对象(在本例中为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 vectorsin lieu of dynamic arrays where possible for a myriad number of reasons as discussed here:

强烈建议vectors在可能的情况下使用动态数组代替动态数组,原因如下所述:

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

在 C++ 中何时使用向量以及何时使用数组?

回答by kmort

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?

这样做你想要的吗?