简体   繁体   English

模式匹配,循环重复次数超出预期

[英]pattern matching for loop repeating more than desired

I've never used string or string functions until today and I'm running into a problem that I don't understand. 直到今天,我从未使用过字符串或字符串函数,并且遇到了一个我不了解的问题。 This program as is, should just accept a command line argument, load the file and display it to memory. 该程序照原样应该只接受命令行参数,加载文件并将其显示到内存中。 However it displays it multiple times. 但是,它将多次显示。 I'm pretty sure the for loop is the problem, but it is the same technique as what is used in the programming reference I am using. 我很确定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++;
            }
    }
}

I see at least one of the problems with my code. 我发现我的代码中至少有一个问题。 I re-wrote the loop as a while loop because it was easier to follow and paid a little more attention to where I am starting and stopping. 我将循环重新编写为while循环,因为它更易于遵循,并更加关注我的开始和停止位置。 However it still seems to be printing twice. 但是,它似乎仍在打印两次。

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 );
            }

This is because you have two printing statements that are displaying the contents of the file. 这是因为您有两个显示文件内容的打印语句。

The first print statement is this one: 第一个打印语句是这样的:

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

The second one is this: 第二个是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM