C++通过引用传递字符串数组

C++ passing a string array by reference

本文关键字:字符串 数组 引用 C++      更新时间:2023-10-16

我是C++的新手,我正在尝试编写一个程序,只使用函数(没有向量或模板)就可以读取extarnal文件并将所有内容保存在一个数组中。为了给我的数组定尺寸,我首先读取文件中的总行数,然后根据它来给数组定尺寸。然后我重新读取文件中的所有行,并开始将它们存储在数组中。一切顺利。但当我得到代码并试图让我们成为一个功能时,我陷入了困境。我找不到任何通过引用传递数组的方法。每次我都会发现各种各样的错误。有人能帮帮我吗?谢谢

while (!infile.eof())
{
// read the file line by line
getline (infile,line);
 ++lines_count2;
// call a function that take out the tags from the line
parseLine(&allLines[lines_count], lines_count2, line);
}   // end while

    // FUNCTION PARSE
    // Within parseHTML, strip out all of the html tags leaving a pure text line.
    void parseLine(string (&allLines)[lines_count], int lines_count2, string line)
{
// I don-t take empty lines
if (line!="")
{
// local var
string del1="<!DOCTYPE", del2="<script";
int eraStart=0, eraEnd=0;
    // I don't take line that start with <!DOCTYPE
    eraStart = line.find(del1);
    if (eraStart!=std::string::npos)
        line.clear();
    // I don't take line that start with  <script
    eraStart = line.find(del2);
    if (eraStart!=std::string::npos)
    line.clear();
    //out
    cout << "Starting situation: " << line << "n n";
    // A. counting the occourence of the character ">" in the line
    size_t eraOccur = count(line.begin(), line.end(), '<');
    cout << "numero occorenze" << eraOccur  << "n n";
    // declaring the local var
    string str2 ("<"), str3 (">");
    // B. loop in the line for each occurence...looking for <  and >  position
    for (int i=0; i<eraOccur; i++)
    {
        // looking for position char  "<"
        eraStart = line.find(str2);
        if (eraStart!=string::npos)
        {
            cout << "first 'needle' found at: " << eraStart << 'n';
            // looking for position char  ">"
            eraEnd = line.find(str3);
            if (eraEnd!=string::npos)
            cout << "second 'needle' found at: " << eraEnd << 'n';
            eraEnd=eraEnd-eraStart+1;
            //delete everything between < and >
            cout << "start " << eraStart  << " end " <<  eraEnd << "n n";     
            line.erase(eraStart, eraEnd);
        }
    }
cout << "memo situation: " << line << "n n";
// C. memorize the result into an array
allLines[lines_count2] = line;
}       // end if

}

假设您的数组被声明为string allLines[lines_count],则应该将函数声明为

void parseLine(string* allLines, int lines_count2, string line)

void parseLine(string allLines[], int lines_count2, string line)

并将函数调用为parseLine(allLines, lines_count2, line)