问题描述
我的项目目录中有一个 .txt 文件,我创建并填充了数据.
I have a .txt file in my project directory that I made and populated with data.
目录结构如下:
/Users/asd/ClionProjects/ProjectWithTemplates/
main.cpp
cmake
twoday.txt
这是我的代码:
#include <iostream>
#include <array>
#include <cmath>
#include <fstream>
using namespace std;
/* print array prototype */
template <size_t N>
void printArray(const array<double , N> & arr);
/* mean function prototype */
template <size_t N>
double meanArray(const array<double , N> & arr);
/* standard deviation prototype */
template <size_t N>
double sDeviation(const array<double , N> & arr);
int main() {
string date1;
string date2;
array<double, 24> day1Temps;
array<double, 24> day2Temps;
array<double, 3> testarr = {75,70,65};
/* TESTING PURPOSES */
printArray(testarr);
sDeviation(testarr);
cout << "standard deviation of array is: " << sDeviation(testarr) << endl;
cout << "mean of array is: " << meanArray(testarr) << endl;
/* END TESTING */
ifstream inputFile;
inputFile.open("twoday.txt");
if(inputFile.is_open())
{
inputFile >> date1;
inputFile >> date2;
for(int i = 1; i < day1Temps.size(); ++i)
{
inputFile >> day1Temps[i];
}
for (int j = 1; j < day2Temps.size(); ++j) {
inputFile >> day2Temps[j];
}
} else cout << "File unable to open. File does not exist." << endl;
return 0;
}
/* print array defination */
template <size_t N>
void printArray(const array<double , N> & arr){
for(const auto & i : arr)
{
cout << i << " ";
}
cout << endl;
}
/* mean function defination */
template <size_t N>
double meanArray(const array<double , N> & arr){
double sum;
for (const auto & i : arr) {
sum+=i;
}
return sum/arr.size();
}
/* standard deviation defination */
template <size_t N>
double sDeviation(const array<double , N> & arr){
double mean = meanArray(arr);
double total;
for (const auto & i : arr){
total+=pow(i - mean, 2);
}
return sqrt(total/arr.size());
}
除了我的文件 IO 之外,其他一切都很好.很奇怪.
Eveything else works fine besides my file IO. Very strange.
添加一些细节……更多细节?:(
adding some details..............more details? :(
推荐答案
if inputFile.is_open()
总是返回 false
, inputFile.open("twoday.txt");
没有正确打开文件,大概是因为找不到 "twoday.txt"
if inputFile.is_open()
always returns false
, inputFile.open("twoday.txt");
is not opening the file correctly, presumably because it can't find "twoday.txt"
如果您使用的是 Linux,请尝试设置显式路径,例如 "c:/path/twoday.txt"
或 "/path/twoday.txt"
.您也可以尝试编写一个文件来查看它出现的位置,或者使用更奇特的方法返回当前路径.
Try setting an explicit path like "c:/path/twoday.txt"
or "/path/twoday.txt"
if you're using Linux. You could also try writing a file instead to see where it shows up, or something more exotic to return the current path.
这篇关于CLion C++ 无法读取/打开项目目录中的 .txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!