[英]file not opening via terminal using g++ file is in same directory
我制作了一个程序来处理用户传入的名称的文件。 当通过 IDE 编译时,我得到了正确的输出,但是当我使用 g++ 通过 MacOS 终端编译和运行时,程序没有捕获输入的文件名,所以我卡在了 while 循环中,代码的 rest 无法运行。
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
double numrows(string name)
{
double index = 0;
string currentline;
fstream myFile;
myFile.open(name);
while(myFile)
{
getline(myFile, currentline);
index++;
if(myFile.eof())
{
myFile.clear();
myFile.seekg(0,ios::beg);
break;
}
}
return index;
}
double findaverage(double numrows, double sum)
{
return (sum/numrows);
}
bool checkifvalid(string victim)
{
for(auto &ch: victim)
if(!(isdigit(ch)))
{
return false;
}
return true;
}
int main()
{
string currentline, number,NaN;
double largest = 0.0;
int index = 0;
double validcount =0.0;
double firstcolsum = 0;
fstream myFile;
bool userinput = false;
string filename;
cout << "please input file name :";
cin >> filename;
myFile.open(filename);
while(!myFile)
{
cout << "file not found please try again.." ;
cin >> filename;
myFile.open(filename);
}
double size = numrows(filename);
while(myFile)
{
getline(myFile, currentline);
stringstream ss(currentline);
while(getline(ss, number, ','))
{
bool valid = checkifvalid(number); // checking if number is valid (in string)
if(valid == false)
{
NaN += number + ",";
}
else
{
double num = stoi(number);
if(index%2 == 0) //check if index even or odd if even then its first row, viceversa
{
firstcolsum += num;
validcount++;
}
else
{
if(num > largest)
largest = num;
}
}
index++;
}
if(myFile.eof())
break;
}
double average = findaverage(validcount, firstcolsum);
cout << fixed<< setprecision(4);
cout << "The average value of all numbers in the first column: " << average << endl;
cout<< setprecision(0);
cout << "The largest value of all numbers in the second column: " << largest<< endl;
cout << "The total number of rows in the file is: " << size << endl;
cout << "The invalid numbers are: " << NaN << endl;
}`
是我当前的代码,它可以通过其他 IDE 运行,但不能运行 g++
我尝试制作新的文件夹和来源,但似乎没有任何效果。
确保您已使用“cd”命令导航到包含源文件和输入文件的文件夹,并且输入文件的名称不包含任何空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.