在 c++ 中循环字符串读取器

Looping a string reader in c++

本文关键字:读取 字符串 循环 c++      更新时间:2023-10-16

我正在做一个项目,该项目获取患者 ID、患者血压记录的数量,显示这些记录,然后根据该患者的 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
reader != "n"

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

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

修复它留作练习。