C++ 我的代码不断返回0作为文本文件中的小数位数
我制作了一个文本文件,里面填充了用空格分隔的小数,我想数一数有多少。问题是,当我来检查是否正确时,程序会说文件中的元素数为0C++ 我的代码不断返回0作为文本文件中的小数位数,c++,C++,我制作了一个文本文件,里面填充了用空格分隔的小数,我想数一数有多少。问题是,当我来检查是否正确时,程序会说文件中的元素数为0 ifstream dataInput("Data Set.txt"); double readNumber; vector<int> dataSet; while (dataInput >> readNumber){ dataSet.push_back(readNumber); } cout << "the Number
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;
我的预期结果是
The number of elements in this file is N.
但我得到的却是:
The number of elements in this file is 0.
编辑:多亏了这里的人,我发现我的文件没有正确打开。我加了一行
if (!dataInput.is_open()) {
cerr << "The file can not be opened\n";
exit(1);//exits the program
}
如果(!dataInput.is_open()){
cerr尝试正确读取文件“ifstream dataInput(“DataSet.txt”);”您应该调试代码以了解是否通过了此条件
>readNumber)>作为建议,您应该熟悉STL,但要知道它需要一些时间来练习。最后,您将能够编写非常简洁的代码
#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;
}
#包括
#包括
#包括
#包括
int main(){
std::ifstream数据输入(“./data/TestFile.txt”);
如果(!dataInput.good())返回EXIT_失败;
向量数据集;
std::copy(std::istream_迭代器(数据输入),std::istream_迭代器(),std::back_插入器(数据集));
std::您能发布一段文本文件吗?请回答您的问题并显示“Data Set.txt”的前6-7行文件。也可以考虑将代码片段转换为一个“代码< > DATAN PUT> > Read No.<代码>评估为<代码> BOOL值。请不要张贴文本图片,张贴文本。@ CHTCXPUU可能有很多原因,但通常是,您认为文件应该在哪里,程序在哪里寻找文件是两个不同的。但是我们会遇到一些问题,比如你如何运行你的程序,你在使用什么操作系统等等。严格地说,这些事情与C++没有任何关系。opened@Jabberwocky:这是一个很好的观点。在这种情况下,我的向量仍然是空的,但原因不是文件不是空的。@JaBBERWORKY:为了解决这个问题,我对它做了一些修改。也许你有更好的解决方案?现在我觉得还可以。注意:OP的文件名中有空格,这可能会导致问题;你的文件名没有。
#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;
}