在开始之前,我会指出我对C ++和一般编程非常陌生,因此,如果我做不正确的事情或以奇怪的方式编写代码,那是因为到目前为止我只学到了很多东西。
无论如何,我被分配了一个程序,首先要写一个程序
唯一要注意的是,我假设我必须在代码内使用动态数组,以便允许文件容纳任意数量的整数。
到目前为止,除了动态数组的实现之外,我已经拥有所有东西。该代码目前被编程为仅接受10个整数(因为代码中尚无数组)。
这是我的代码:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
//Variables
string inFile;
int numbers, i = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double count = 0, neg_count = 0, pos_count = 0;
char answer;
do
{
//Input Question
cout << "Enter the file name.\n";
cin >> inFile; // Input from User
ifstream fin; // Open File
fin.open(inFile);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
while (count < 10)
{
fin >> numbers;
if (numbers >= i)
{
sum += numbers;
count += 1;
pos_count += 1;
}
if (numbers < i)
{
neg_sum = neg_sum + numbers;
count = count + 1;
neg_count = neg_count + 1;
}
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / 10.0;
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
任何帮助将不胜感激! 预先感谢
更新:
我已经走了这么远,但是当我编译时,程序会连续运行。不确定我做错了什么。
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
//Variables
string file;
int i = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double neg_count = 0, pos_count = 0, totcount = 0;
char answer;
//Input Question
do
{
cout << "Enter the file name.\n";
cin >> file; // Input from User
ifstream fin; // Open File
fin.open(file);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
while (!fin.eof())
{
int numbers;
fin >> numbers;
int *dynamicArray;
dynamicArray = new int[numbers];
if (numbers >= i)
{
sum += numbers;
pos_count += 1;
totcount += 1;
}
if (numbers < i)
{
neg_sum = neg_sum + numbers;
neg_count = neg_count + 1;
totcount += 1;
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / totcount;
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
delete [] dynamicArray;
}
fin.close();
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
更新:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
//Variables
string file;
int i = 0, value = 0, e = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0, neg_sum = 0;;
double neg_count = 0, pos_count = 0, totcount = 0;
char answer;
//Input Question
do
{
cout << "Enter the file name.\n";
cin >> file; // Input from User
ifstream fin; // Open File
fin.open(file);
if (fin.fail()) // Check to see if file opens properly
{
cout << "An error occurred while attempting to open the file.\n";
exit(1);
}
// <---------- This works to get the size of the file
int elements;
vector<int> eCount;
while (fin >> elements)
{
eCount.push_back(elements);
}
int size = static_cast<int> (eCount.size());
cout << "size = " << size << endl;// <-----------Test to see if working
//From this point, size of the file is held in the variable, 'size'.
int array_size = size;
int* p;
p = new int[array_size];
int location = 0;
while (!fin.eof())
{
fin >> p[location];
location++;
}
cout << "P[12] is equal to " << p[12] << endl;// <----Test to see if array is initialized
while (fin >> p[location])
{
if (p[e] >= i)
{
sum = sum + p[location];
pos_count = pos_count + 1;
totcount = totcount + 1;
}
else
{
neg_sum = neg_sum + p[location];
neg_count = neg_count + 1;
totcount = totcount + 1;
}
location++;
}
//Calculations
avg = sum / pos_count;
neg_avg = neg_sum / neg_count;
total_sum = sum + neg_sum;
total_avg = total_sum / totcount;
fin.close();
//OUTPUT
cout << "The sum of all positive numbers is: " << sum << endl;
cout << "The average of all positive numbers is: " << setprecision(3) << avg << endl;
cout << "The sum of all negative numbers is: " << neg_sum << endl;
cout << "The average of all negative numbers is: " << setprecision(3) << neg_avg << endl;
cout << "The sum of all numbers is: " << total_sum << endl;
cout << "The average of all numbers is: " << setprecision(3) << total_avg << endl;
cout << "-------------------------------------------------" << endl;
cout << "Want us to read another file?\n";
cout << "Enter 'Y' or 'y' for yes, any other character for no." << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
感谢所有参与的人。我希望我不必使用动态数组,但是不幸的是,如果不实现动态数组,我将不会收到。我更新了代码,但似乎无法正常运行数组,因为它似乎无法正确加载文件中的输入。任何帮助!
答案 0 :(得分:1)
好吧,您遇到的最大I / O问题是尝试使用while (!fin.eof())
进行读取。参见Why !.eof() inside a loop condition is always wrong.。您遇到的最大逻辑问题是在从文件读取整数的同一循环中包含//Calculations
。
由于您读取并整型并保持正值和负值的连续和,因此根本不需要动态数组。当前,您保留pos_count, neg_count, and totcount
,这是离开读循环时计算各自平均值所需的全部。
要整理一些东西,让我们看一下您的变量。虽然您可以将double
用于pos_count, neg_count, and totcount
,但最好将unsigned
类型用于计数器。 C ++提供size_t
作为计数和长度的首选 sizetype ,但这不是强制性的-只是说得通。虽然您可以使用单独的file
和answer
,但最好将每个输入都读入std::string
以确保一次击键(例如用户输入"Yes"
而不是{ {1}})不会在'Y'
中保留未读的其他字符。您还可以对stdin
和std::string
使用相同的file
,只需检查第一个字符是answer
还是'y'
来控制另一个字符的读取文件循环。
综上所述,您的变量可以很简单:
'Y'
(注意:,将答案读入缓冲区是在int main (void) {
std::string buffer; /* use single buffer for filename & answer */
do
{ // Variables (will be reinitialized for each file)
int number; /* you are reading one number at a time */
size_t neg_count = 0, pos_count = 0, totcount = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0., neg_sum = 0.;
循环之前必须声明的唯一变量,才能最终用作测试条件)
如果您什么都不记得了,请记住验证每个输入,例如
do {...} while();
虽然您可以检查流上是否设置了 std::cout << "Enter the file name: ";
if (!(std::cin >> buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
位,但更通用的测试是是否未设置文件流.fail()
,例如
goodbit
(注意:两种方法都可以使用)
在循环中读取时,请以成功读取为条件来调整循环。您在此处的读取循环仅需:
std::ifstream fin(buffer); // open file stream
if (!fin.good()) { // Check to see if file opens properly
std::cerr << "error: file open failed - " << buffer << ".\n";
return 1;
}
这将从文件中捕获您需要的所有信息。现在进行平均计算,但是如果 while (fin >> number) { /* control read loop with read itself */
if (number >= 0) { /* handle positive numbers */
sum += number;
pos_count += 1;
}
else { /* if it's not >= 0, it's negative */
neg_sum = neg_sum + number;
neg_count = neg_count + 1;
}
totcount += 1; /* total count incremented each time */
}
fin.close();
会发生什么。除以零通常是一件非常非常糟糕的事情。始终验证您的分母,例如
pos_count, neg_count, or totcount == 0
现在输出。您要为一个连续的输出块调用 // Calculations
if (pos_count > 0)
avg = sum / pos_count;
else
avg = 0;
if (neg_count > 0)
neg_avg = neg_sum / neg_count;
else
neg_avg = 0;
total_sum = sum + neg_sum;
if (totcount > 0)
total_avg = total_sum / totcount;
else
total_avg = 0;
多少次? (提示:一次)
cout
可在一次调用中处理所有输出需求(包括对 //OUTPUT (you only need one std::cout)
std::cout << "\nThe sum of all positive numbers is: "
<< sum << std::endl
<< "The average of all positive numbers is: "
<< std::setprecision(3) << avg << std::endl
<< "The sum of all negative numbers is: "
<< neg_sum << std::endl
<< "The average of all negative numbers is: "
<< std::setprecision(3) << neg_avg << std::endl
<< "The sum of all numbers is: " << total_sum << std::endl
<< "The average of all numbers is: " << std::setprecision(3)
<< total_avg << std::endl
<< "-------------------------------------------------\n\n"
<< "Want to read another file?\n"
<< "Enter 'Y' or 'y' for yes, any other character for no.\n";
或'Y'
的提示)。现在只需使用相同的'y'
来输入是否继续,例如
std::string
就是这样,您完成了。放在一起,用 if (!(std::cin >> buffer)) {
std::cerr << "(user canceled input)\n";
return 1;
}
/* condition on 1st char in buffer */
} while ((buffer.at(0) == 'y') || (buffer.at(0) == 'Y'));
}
代替对std::cin >> buffer
的脆弱使用,您将拥有:
getline (std::cin, buffer)
(注意: #include <iostream>
#include <fstream>
#include <iomanip>
int main (void) {
std::string buffer; /* use single buffer for filename & answer */
do
{ // Variables (will be reinitialized for each file)
int number; /* you are reading one number at a time */
size_t neg_count = 0, pos_count = 0, totcount = 0;
double avg, neg_avg, total_sum, total_avg, sum = 0., neg_sum = 0.;
std::cout << "Enter the file name: ";
if (!getline(std::cin, buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
std::ifstream fin(buffer); // open file stream
if (!fin.good()) { // Check to see if file opens properly
std::cerr << "error: file open failed - " << buffer << ".\n";
return 1;
}
while (fin >> number) { /* control read loop with read itself */
if (number >= 0) { /* handle positive numbers */
sum += number;
pos_count += 1;
}
else { /* if it's not >= 0, it's negative */
neg_sum = neg_sum + number;
neg_count = neg_count + 1;
}
totcount += 1; /* total count incremented each time */
}
fin.close();
// Calculations
if (pos_count > 0)
avg = sum / pos_count;
else
avg = 0;
if (neg_count > 0)
neg_avg = neg_sum / neg_count;
else
neg_avg = 0;
total_sum = sum + neg_sum;
if (totcount > 0)
total_avg = total_sum / totcount;
else
total_avg = 0;
//OUTPUT (you only need one std::cout)
std::cout << "\nThe sum of all positive numbers is: "
<< sum << std::endl
<< "The average of all positive numbers is: "
<< std::setprecision(3) << avg << std::endl
<< "The sum of all negative numbers is: "
<< neg_sum << std::endl
<< "The average of all negative numbers is: "
<< std::setprecision(3) << neg_avg << std::endl
<< "The sum of all numbers is: " << total_sum << std::endl
<< "The average of all numbers is: " << std::setprecision(3)
<< total_avg << std::endl
<< "-------------------------------------------------\n\n"
<< "Want to read another file?\n"
<< "Enter 'Y' or 'y' for yes, any other character for no.\n";
if (!getline(std::cin, buffer)) {
std::cerr << "(user canceled input)\n";
return 1;
}
/* condition on 1st char in buffer */
} while ((buffer.at(0) == 'y') || (buffer.at(0) == 'Y'));
}
已在上面的代码中使用,以使用户输入更加健壮-出于示例原因,请参见示例输出下面的部分)>
使用/输出示例
使用三个文件进行测试,第一个文件是一组50x5的正整数集,然后是一组包含一个负值(getline (std::cin, buffer)
)的10个整数,最后一个文件是100个正负混合值。
-2213
有很多方法可以将其组合在一起,并且您可以随意使用任意多个变量或对$ ./bin/pos_neg_total
Enter the file name: dat/50x5.txt
The sum of all positive numbers is: 122180
The average of all positive numbers is: 489
The sum of all negative numbers is: 0
The average of all negative numbers is: 0
The sum of all numbers is: 1.22e+05
The average of all numbers is: 489
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
y
Enter the file name: ../../..//src-c/tmp/dat/10int_nl.txt
The sum of all positive numbers is: 2.03e+05
The average of all positive numbers is: 786
The sum of all negative numbers is: -2.21e+03
The average of all negative numbers is: -2.21e+03
The sum of all numbers is: 2.01e+05
The average of all numbers is: 774
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
Y
Enter the file name: ../../../src-c/tmp/dat/100int.txt
The sum of all positive numbers is: 1.93e+06
The average of all positive numbers is: 5.55e+03
The sum of all negative numbers is: -2.29e+05
The average of all negative numbers is: -1.76e+04
The sum of all numbers is: 1.7e+06
The average of all numbers is: 4.71e+03
-------------------------------------------------
Want to read another file?
Enter 'Y' or 'y' for yes, any other character for no.
n
的调用,但是希望这将有助于您进一步思考“我的程序需要吗?”。
使用std::cout
进行用户输入很容易
最后,请注意,使用>>
进行用户输入非常脆弱,因为将不会读取用户键入作为输入一部分的任何空格(并且将其保留为未读std::cin >> string
中的em>,最好使用stdin
,它将完整的行读入您的字符串中。请勿将getline
iostream与>>
输入一起使用不说明getline
中可能剩余的'\n'
,然后可以使用stdin
进行清除。这种情况下,这样做更加健壮所有带有std::cin.ignore()
的用户输入,例如
getline
然后可以正确处理带有whtespace的文件名,如果用户想输入 if (!getline(std::cin, buffer)) { // VALIDATE Input from User
std::cerr << "(user canceled input)\n";
return 1;
}
作为您对继续问题的回答,那将完全没有问题。如果您还没有上课,请把它放在臀部口袋里。为了进行实验,请尝试用上面的原始"Yes I want to enter another file!"
替换上面显示的两个用户输入,然后查看在提示符std::cin >> buffer
上键入"Yes I want to enter another file!"
会发生什么情况
如果您还有其他问题,请告诉我。
答案 1 :(得分:0)
所以为什么需要一个向量(动态数组)来存储整数,因为您的代码可以通过在EOF条件下添加一个“ break”表达式来处理所有情况。 如果您确实需要它,则下面是您需要的:
app.use(function (req, res, next)
{
res.locals.toasts = req.toastr.render()
next()
});