【问题标题】:pattern matching for loop repeating more than desired循环重复的模式匹配超出预期
【发布时间】:2016-03-20 18:24:35
【问题描述】:

直到今天我才使用字符串或字符串函数,我遇到了一个我不明白的问题。这个程序应该只接受一个命令行参数,加载文件并将其显示到内存中。但是它会多次显示它。我很确定 for 循环是问题所在,但它与我正在使用的编程参考中使用的技术相同。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

char* getFile( char* fileName ){
    std::fstream inFile( fileName );
    if( !inFile ) std::cout << "Could not open " << fileName << ".\n";
    else{
        inFile.seekg(0,inFile.end);
        int len = inFile.tellg();
        inFile.seekg(0,inFile.beg);
        char* buffer = new char[len];
        inFile.read( buffer, len);
        inFile.close();
        std::cout.write(buffer,len);
        return buffer;
        }

    }
int main(int argc, char** argv){
    if(argc != 2) std::cout << "Parameter required\n";
    else{
        std::string f = getFile( argv[1] );
        for( size_t i = f.find( 0x0A, 0 ); i != std::string::npos ; i = f.find( 0x0A, i) ){
            std::cout << f.substr(0,i)<<std::endl;
            i++;
            }
    }
}

我发现我的代码至少有一个问题。我将循环重写为 while 循环,因为它更容易遵循并且更加注意我开始和停止的位置。但是,它似乎仍然打印了两次。

int main(int argc, char** argv){
    if(argc != 2) std::cout << "Parameter required\n";
    else{
        std::string f = getFile( argv[1] );
        size_t start = 0;
        size_t end = 1;
        while( end != std::string::npos ){
            end = f.find( 0x0A, start );
            std::cout << f.substr(start,end)<<std::endl;
            start = ( end + 1 );
            }

【问题讨论】:

  • i++ 不能做到这一点吗?
  • 你想达到什么目的?根据换行符的位置拆分字符串 f?并在新行上打印每个部分?
  • 是的。代码按原样工作,只是它多次打印文件。不是一个连续的循环,而是很多次。
  • 首先,现在编写了算法,以便为每个匹配项打印一个从开始到匹配项的子字符串。因此,它将打印第一行,然后是第一行和第二行,然后是第一行、第二行和第三行,等等。跟踪您开始搜索的位置。更新每次迭代。尝试在调试器中单步调试代码,看看到底发生了什么。

标签: c++ string for-loop substring


【解决方案1】:

这是因为您有两个显示文件内容的打印语句。

第一个打印语句是这个:

std::cout.write(buffer,len);

第二个是这样的:

std::cout << f.substr(0,i)<<std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2019-05-05
    • 2012-08-31
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多