C 从具有不同数据类型的文件中循环
c++ while loop from file with different data types
我有一个包含此信息的文件:
Bev Powers
3
76 81 73
Chris Buroughs
5
88 90 79 81 84
Brent Mylus
2
79 81
我有一个控制的循环,该循环将执行前3行并正确使用信息,但是我正在努力使用一个循环,该循环将重复使用循环,直到从文件中显示所有信息,无论有多少匹配匹配的高尔夫球手在文件上。我要求朝着正确方向的指针,任何帮助都将不胜感激。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream inScores;
string filename;
string name;
int loopCount, matchScore;
int count = 1;
float mean = 0;
float adder = 0;
int main()
{
cout << endl << "Enter the golfer's filename: ";
getline(cin,filename);
cout << endl;
inScores.open(filename.c_str());
if(!inScores)
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << endl << endl;
return 1;
}
getline(inScores,name);
inScores >> loopCount;
cout << name << " has " << loopCount << " matches with scores of" << endl << endl;
inScores >> matchScore;
while (count <= loopCount)
{
cout << "Match " << count << ": " << matchScore << endl;
adder = adder + matchScore;
adder = adder + matchScore;
inScores >> matchScore;
count++;
}
cout << endl;
int(mean) = .5 + (adder / loopCount);
cout << "The mean score is " << mean << endl << endl;
inScores.close();
return 0;
}
如使用循环所述,要获得所需的东西。另外,由于getline和提取返回false如果失败了,则可以在循环中使用它们进行测试:
ifstream inScores;
string filename;
string name;
int loopCount , matchScore;
int count = 1;
float mean = 0;
float adder = 0;
int main()
{
cout << endl << "Enter the golfer's filename: ";
getline( cin , filename );
cout << 'n';
inScores.open( filename );
if ( !inScores )
{
cout << "** " << filename << " does not exist. Please ";
cout << "check the spelling and rerun ";
cout << "the program with an existing golfer file. ** " << "nn";
return 1;
}
while ( getline( inScores , name ) )
{
if ( inScores >> loopCount )
{
cout << name << " has " << loopCount << " matches with scores of" << "nn";
}
else
{
cout << "File read error";
return 1;
}
for ( int count = 1; count <= loopCount; count++ )
{
if ( inScores >> matchScore )
{
cout << "Match " << count << ": " << matchScore << 'n';
adder = adder + matchScore;
}
else
{
cout << "File read error";
return 1;
}
}
}
cout << 'n';
int( mean ) = .5 + ( adder / loopCount );
cout << "The mean score is " << mean << "nn";
inScores.close();
return 0;
}
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 使用fstream对txt文件中的数字进行循环
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- C/C++:socket() 创建在循环中失败,打开的文件太多
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 虽然循环不读取整个 ifstream 文件
- 如何在头文件中声明类模板(由于循环依赖关系)
- 如何使用循环逐个读取C++中的多个文件
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 如何循环 n 次,在 xml 文件中每个循环一个级别
- 如何通过一个循环将多个文件的内容分配给不同的类属性?
- 从文件 C++ 读取时的无限循环
- 从文件读取,并循环访问文件以写入数组
- 从文件导入数据时遇到问题.我有一个没完没了的循环
- C++:从文件中读取x y数据会产生无限循环吗
- 从文件循环输入的更合适方法?
- 通过C(或C )中的WAV文件循环
- 有没有办法仅通过JPG文件循环
- 从文件循环输入流
- c++单文件循环引用