[英]C++ Basic While Loop: Unknown Inputs and Value Increment
所以我正在尝试编写一个程序,从具有标记0的数据文件中读取未知输入,或者我猜测循环的终止点。
来自数据文件的两个未知输入示例:
这是我的程序(没有“计数”,因为这是我的问题所在):
int main()
{
//Declaring variables.
int input, lines, count, totalcount, datafile;
lines = 0;
count = 0;
totalcount = 0;
//Loop runs as long as data file has an integer to take in.
while(cin >> datafile)
{
//If datafile is not 0, loop runs until datafile is 0.
while(datafile != 0)
{
//Counts all integers in the file except 0.
totalcount += 1;
cin >> datafile;
}
//Counts how many lines there are in a data file using sentinel 0 (not "/n").
if(datafile == 0)
lines += 1;
//Outputs.
cout << lines << setw(11) << count << setw(11) << totalcount << endl;
}
return 0;
}
除了逻辑/概念本身之外,请不要担心技术性,效率或其他任何问题,因为我只是想在我的知识中找到缺失的链接来完成这项任务。
话虽如此,我的预期输出格式如下:
“行#”“每行整数计数”“数据文件中所有整数的总计”
使用我当前代码的示例一 ,我会有输出(间距不精确,'。'代表空白):
1 ...... 0 ...... 3
2 ...... 0 ...... 7
正确的预期产出:
1 ...... 3 ...... 3
2 ...... 4 ...... 7
我想要任何提示或解释我如何计算每行的整数(在sentinel 0之前)并将该值赋给“int count”而不将值保持到下一行。
我是一名入门C ++课程的学生,所以请向我展示一个基本的方法,我将如何首先解决这个问题,然后根据未来的应用需要提供其他任何高级选项。
行为准则个人陈述:
通过参与,您将为完成作业提供必要的知识,而不是完成作业本身。 我使用的示例是出于概念演示目的而生成的,并且只是最终作业的一小部分。
10/23/2016 9:56 PM更新1:
目前正试图使用“temp”变量从“totalcount”中减去。 如果尝试成功,我将更新我的代码。
totalcount是计数的总和。 这是我的建议
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declaring variables.
int input, lines, count, totalcount, datafile;
lines = 0;
count = 0;
totalcount = 0;
//Loop runs as long as data file has an integer to take in.
while(cin >> datafile)
{
// Add count to totalcount and reset count each time reach 0
if (datafile == 0) {
totalcount += count;
lines += 1;
cout << lines << setw(11) << count << setw(11) << totalcount << endl;
count = 0;
}
//otherwise increase count
else {
count++;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.