试图从txt文件中读取两段数据并将其输出[C ++]

问题描述 投票:-1回答:1

txt file

class calcBMI {
    public:
        string line;
        string line2;
        fstream search;
        short loop = 0;
        string weight[6];
        string height[6];
        int index[6] = { 1, 2, 3, 4, 5 };
        int i;

        void getHeight();
        void getWeight();

    };

void calcBMI::getWeight() {

    search.open("name.txt"); //Opens the text file in which the user details are stored
    if (search.is_open())
    {
        while (getline(search, line) && (getline(search, line2))) { //While the program searches for the lines in the text file
            if (line.find("Current Weight(KG): ") != string::npos && (line2.find("Height(Metres)") != string::npos)) { //If the string "Name" isnt the last word on the line
                weight[loop] = line; //Assings the strings read from the text file to the array called weight
                height[loop] = line2;
                cout << index[loop] << ". " << weight[loop] << ", " << height[loop] << endl; //Outputs the index array which loops through the numbers in the array and outputs the weight variable which loops through the strings in the array
                loop++; //Iterates the loop 

            }

        }

    }

}

因此,我试图从包含5个用户的txt文件中读取两段数据。存储的有关用户的数据是他们的姓名,身高,体重和以前的体重。文件的布局/格式如下。

  • 名称:迈克尔
  • 当前重量(KG):65
  • 先前的四次重量测量:67、69、75、72
  • 身高(米):1.7

我正在尝试通过使用以下代码来读取用户的身高和体重,但是当我运行代码时,程序不会输出任何内容。

程序应打印:

  1. 当前高度(KG):00,高度(米):00
  2. 当前高度(KG):00,高度(米):00
  3. 当前高度(KG):00,高度(米):00
  4. 当前高度(KG):00,高度(米):00
  5. 当前高度(KG):00,高度(米):00

但是,它什么也不打印。

c++ loops fstream getline
1个回答
0
投票

这是一个非常快速的解决方案,虽然它不是很好,但是可以使用。将您的代码更改为此:

while (getline(search, line) && getline(search, line) && (getline(search, line2)) && (getline(search, line2))) { //While the program searches for the lines in the text file
            if (line.find("Current Weight(KG): ") != string::npos && (line2.find("Height(Metres)") != string::npos)) { //If the string "Name" isnt the last word on the line
                weight[loop] = line; //Assings the strings read from the text file to the array called weight
                height[loop] = line2;
                cout << index[loop] << ". " << weight[loop] << ", " << height[loop] << endl; //Outputs the index array which loops through the numbers in the array and outputs the weight variable which loops through the strings in the array
                loop++; //Iterates the loop 

            }

        }
© www.soinside.com 2019 - 2024. All rights reserved.