C++ 输出错误的数字C++;
我写了这段代码,我需要一些帮助 正如您从下面的图片中看到的,我很难找到解决此问题的方法。 我正在提交我的代码,结果如下 链接中有图片: 对于第一张图片,我想解决“12”问题 !![图片1]( 对于第二张图片,我想修正它,好像没有有效的数字来输出“无法计算平均值” ![pic2]( 对于最后一张图片,我需要修复-0.00问题 ![pic3]( 就这些 编译命令: g++lesson7part2.cpp-Wall-Wextra-Wuninitialized-pedanticerrors-Wconversion-oa.outC++ 输出错误的数字C++;,c++,c++11,visual-c++,C++,C++11,Visual C++,我写了这段代码,我需要一些帮助 正如您从下面的图片中看到的,我很难找到解决此问题的方法。 我正在提交我的代码,结果如下 链接中有图片: 对于第一张图片,我想解决“12”问题 !![图片1]( 对于第二张图片,我想修正它,好像没有有效的数字来输出“无法计算平均值” ![pic2]( 对于最后一张图片,我需要修复-0.00问题 ![pic3]( 就这些 编译命令: g++lesson7part2.cpp-Wall-Wextra-Wuninitialized-pedanticerrors-Wconv
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ofstream outFile;
string outFileName = "invalid-numbers.txt";
char filename[]="";
cin>>filename;
ifstream in(filename);
if (!in.good())
{
cout<<"File " << "\""<< filename <<"\"" << " could not be opened" <<endl;
exit(0);
}
outFile.open(outFileName.c_str()); //open file
if (!outFile) { //check if u opened file properly or not
cout << "Error opening " << outFileName << " " << endl;
return 1;
}
double inNumber = 0;
double valTotal = 0;
double countValNum = 0;
double count =0;
while (in >> inNumber) {
if (inNumber >= 0 && inNumber <= 110) {
valTotal += inNumber;
countValNum++;
} else {
outFile << inNumber << fixed << setprecision(2) << endl;
}
count++;
}
cout << "Reading from file " << "\""<< filename <<"\"" << endl;
cout << "Total values: " << count << endl;
cout << "Invalid values: " << (count - countValNum) << endl;
cout << "Valid values: " << countValNum << endl;
cout << "Average of valid values: " << fixed << setprecision(2) << (valTotal / countValNum) << endl;
outFile.close();
in.close();
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
出流孔的直径;
字符串outFileName=“无效的数字.txt”;
字符文件名[]=“”;
cin>>文件名;
ifstream-in(文件名);
如果(!in.good())
{
cout您试图在此处读取单个元素数组:
char filename[]="";
cin>>filename;
这将损坏您的内存。您需要为文件名字符串分配一些大小。例如:
char filename[256] = "";
将为长度最多为256个字符的文件名执行此操作
把它放在一边,Car []是C构造。你使用C++,所以你也应该用C++的方式做事情。而不是简单的数组使用C++字符串或StrugSu水流。它会使你的工作变得容易很多。
std::string filename{};
cin >> filename;
使用std::string而不是char数组。char filename[]=”;
读取的filname可以有多长?