简体   繁体   English

我的代码不断返回0作为文本文件中的小数位数

[英]My code keeps returning 0 as the number of decimals in a text file

I made a text file filled with decimals that are separated by a space and I want to count how many there are. 我制作了一个文本文件,该文件填充有用空格分隔的小数,我要计算有多少。 the problem is when I came to check if I did it correctly the program says that the number of elements in the file is 0. 问题是当我来检查是否做得正确时,程序说文件中的元素数为0。

ifstream dataInput("Data Set.txt");
double readNumber;
vector<int> dataSet;
while (dataInput >> readNumber){
        dataSet.push_back(readNumber);
}
cout << "the Number of elements in this file is " << dataSet.size() << endl;

txt file: txt文件:

3.2 1.9 2.7 2.4 2.8 2.9 3.8 3.0 2.5 3.3 1.8 2.5 3.7 2.8 2.0 3.2 2.3 2.1 2.5 1.9

My expected result is 我的预期结果是

The number of elements in this file is N.

but instead I get: 但是我得到了:

The number of elements in this file is 0.

EDIT: Thanks to the people on here I discovered that my file wasn't opening properly. 编辑:感谢这里的人们,我发现我的文件无法正常打开。 I added the line 我加了线

if (!dataInput.is_open()) {
    cerr << "The file can not be opened\n";
    exit(1);//exits the program
}

to check if the file opens properly. 检查文件是否正确打开。

As an advice you should get acquainted with the STL, but be aware that it takes some times to practice. 作为建议,您应该熟悉STL,但要注意它需要花一些时间来练习。 At the end you will be able to write very concise code. 最后,您将能够编写非常简洁的代码。

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>

int main() {
    std::ifstream dataInput("./data/TestFile.txt");
    if (!dataInput.good()) return EXIT_FAILURE;
    std::vector<double> dataSet;
    std::copy(std::istream_iterator<double>(dataInput), std::istream_iterator<double>(), std::back_inserter(dataSet));
    std::cout << "The number of elements in this file is: " << dataSet.size() << "\n";
    return EXIT_SUCCESS;
}

You shouldn't also write using namespace std in order to write less code. 您也不应using namespace std编写代码,以减少代码编写量。 It is considered a bad practice. 这被认为是不好的做法。

Try to read your file correctly " ifstream dataInput("DataSet.txt"); " you should debug your code to know if you passe this condition 尝试正确读取文件“ ifstream dataInput(” DataSet.txt“);”您应该调试代码以了解是否通过了此条件

<< while (dataInput >> readNumber) >> << while(dataInput >> readNumber)>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM