【问题标题】:C++ | Counting Lines in a File between two specific points [closed]C++ |计算文件中两个特定点之间的行数[关闭]
【发布时间】:2014-09-29 04:52:17
【问题描述】:

我最近刚开始使用 c++,很想知道如何计算文件中特定点之间的行数。我已经可以成功找到我想开始计数的第一个点,但我不知道如何进一步计算。

这是我目前得到的:

ifstream fin;
string line;

char* search = "Key:";
char* search2 = "Color:";

// Open the file.
fin.open(filename);

// Check if it was successful in opening the file.
if (fin.fail() == true)
{
    return false;
}

// Read from the file and continue to read until the end of the file is reached.
while (getline(fin, line)) {

    if (line.find(search, 0) != string::npos) {
        //Start counting line ??
    }
}

非常感谢您的帮助。

【问题讨论】:

标签: c++ string file search counting


【解决方案1】:

首先你需要一个变量来存储计数,然后你还需要一个变量来确定你当前是否在计数:

int count = 0;
bool counting = false;

while(...) {
  if(...)
    counting = true;

  if(...)
    counting = false;

  if(counting)
    ++count
}

【讨论】:

    【解决方案2】:

    使用您的代码,例如:

    unsigned int count_lines=0;
    unsigned int ignore_lines=0;
    
    // Read from the file and continue to read until the end of the file is reached.
    while (getline(fin, line)) {
        count_lines++;
        if (line.find(search, 0) != string::npos) {
            ignore_lines = count_lines;
        }
        if (line.find(search2, 0) != string::npos) {
            // The number of rows is count_lines - ignore_lines
        }
    }
    

    【讨论】:

    • 是的,我只是想复杂而不是使用简单的计数器变量,但是谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多