用c ++循环一个字符串阅读器

时间:2013-10-07 20:22:20

标签: c++ while-loop do-while

我正在研究一个项目,该项目需要患者身份,患者血压记录数量,显示这些记录,然后根据该患者的1个或多个血压记录获取平均血压读数。从文件中读取所有数据。这是我到目前为止的代码,

#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

int main()
{

    //Initialize Required Variables For Program
    int patientCount = 0;
    string id;
    string rHowMany; //String To Read From File
    int howMany = 0;
    int howManyCount = 0;
    int avg = 0;
    int avg2;
    string line;
    int numbre_lines = 0;
    ifstream reader ("data.txt"); //Open The Data File To Be Read From

    do
    {
        reader >> id;
        reader >> howMany;
        cout << "The Patient ID Is: " << id << endl;
        cout << "The Number Of Blood Pressure Record This Patient Has Is: " <<
                     howMany << endl;
        do
        {
            reader >> avg;
            avg = avg + avg;
        }
        while (reader != "\n");
        cin.clear();
        avg = avg / howMany;
        cout << "The Patient Average BP Reading Is: " << avg;
    }
    while (!EOF);
    return 0;
}

我尝试使用for循环和while循环,但是得到了一些我无法解决的奇怪错误。所以我决定用嵌套的while循环来做。不幸的是,代码只是在执行时冻结。数据文件在那里,其中包含正确的数据,但由于某种原因,我无法让程序运行。如果有人可以帮助我,我会非常感激。

- 编辑 以下是其中一个文件

4567 4 180 140 170 150
5643 2 125 150

1 个答案:

答案 0 :(得分:0)

reader != "\n"

始终为true,因为readerifstream而“\ n”是字符串文字。
即使两者都转换为void*(我怀疑它显然已编译),将reader转换为void*的结果将永远不会成为文字的地址。

你的逻辑也有点瑕疵 - 如果循环工作,avg将是读取的最后一个值的两倍。

将其修复为练习。