首页 > 解决方案 > bool 函数不能作为 while 条件工作

问题描述

我正在尝试检查文件是否已成功打开,从中读取并在一个函数中输出我从其中读取的所有内容,因为我有 7 个文件要在相同的代码中操作,我想避免编写相同的一遍又一遍的代码。

所以我做了一个bool函数并将其作为while条件。

如果我成功了,函数就会返回true,如果我不成功,它就会返回false。所以while(!function)应该继续尝试直到它起作用,对吗?答案是肯定的,它按预期工作。

但是,如果我将 while 的条件更改为while(function)一个期望重复该功能,直到它以某种方式失败(也许它无法打开文件。)。但它的行为并不像预期的那样。它仅在第一次while迭代时才能正常工作。

这是一个例子:

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <fstream>
#include <sstream>

bool readConfig(std::fstream& file, std::string (&str)[10], std::string identity) {
  if(file.is_open()) {
    if(file.seekg(0)) {
      std::cout<<"Start from 0"<<std::endl;
    }
    // Get content line by line of txt file
    int i = 0;
    while(getline(file, str[i++]));
    std::cout<<"i= "<<i<<std::endl;
    for(int k = 0; k<i; k++) {
    std::cout<<identity<<" = "<<str[k]<<std::endl;
    }
    return true;
  } else {
    std::cout<<"ERROR ! Could not open file."<<std::endl;
    return false;
  }
}

int main() {

    char configFilePath[]="test.txt";
    std::fstream configFile;

    configFile.open(configFilePath, std::fstream::in);
    std::string test[10];
    std::string id = "testing";
    while(!readConfig(configFile, test,id)) {
        usleep(1000*1000);
    };

    return 0;
}

这是的内容test.txt

line 1
line 2
line 3
line 4

这是输出:

Start from 0
i= 5
testing = line 1
testing = line 2
testing = line 3
testing = line 4
testing = 
i= 1
testing = line 1
i= 1
testing = line 1

等等。

为什么它在第一次迭代时起作用,但随后停在i=1? 我问是因为我不知道我所做的是否正确。while(!function)工作,但也许它不会一直工作,也许我的代码有缺陷。

或者也许while(getline(configFile, string[i++]));是这里的错?

这是我要替换的代码:

void readConfig(std::fstream& configFile, std::string (&str)[10], std::string identity) {
  if(configFile) {
    // Get content line by line of txt file
    int i = 0;
    while(getline(configFile, str[i++]));
    //for debug only
    if((i-1) == 0) {
      std::cout<<identity<<" = "<<str[i-1]<<std::endl;
    } else {
      for(int k = 0; k<i-1; k++) {
        std::cout<<identity<<" = "<<str[k]<<std::endl;
      }
    }
  } else {
    log("ERROR ! Could not get content from file.");
  }
}

int main() {
file.open(file, std::fstream::in);
    if(file.is_open()) {
      std::cout<<"Successfully opened URL Display Text file."<<std::endl;
      std::string inputs[10];
      std::string id = "url_text";
      readConfig(file, inputs, id);
      file.close();
    } else {
      // Could not open file
      log("Error ! Could not open file.");
    }
}

我这样做了 7 次,而不是仅仅调用一个函数 7 次,而是完成了所有这些。

标签: c++

解决方案


但是,如果我将 while 的条件更改为 while(function),人们会期望重复该函数,直到它以某种方式失败(也许它无法打开文件。)。

你的推理在这里关闭。该函数没有打开文件,因此当它在第一次成功时,在下一次迭代中不会出错。

该函数的作用是:它读取文件的所有内容,然后返回true. 随后的迭代没有什么可读的,但函数仍然返回true

您应该检查文件是否只打开一次,而不是在每次迭代中打开。如果该函数应该读取一行,那么就这样做,目前它读取所有。


推荐阅读