【问题标题】:C++ passing a string array by referenceC++ 通过引用传递字符串数组
【发布时间】:2014-04-26 21:17:06
【问题描述】:

我是 C++ 新手,我正在尝试编写一个仅使用函数(无向量或模板)应该能够读取外部文件并将所有内容保存在一个数组中的程序。 为了确定我的数组的尺寸,我首先读取文件中的总行数,并基于此确定我的数组的尺寸。 然后我重新读取文件中的所有行并开始将它们存储在数组中。 一切顺利。 但是当我得到代码并试图让我们成为一个功能时,我被卡住了。 我找不到通过引用传递数组的任何方法。 每次我发现各种错误。 有人能帮助我吗? 谢谢

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

}

【问题讨论】:

标签: c++ arrays string function parameter-passing


【解决方案1】:

假设你的数组被声明为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)

【讨论】:

  • 是的尤达!是的....谢谢。我正在寻找不同的解决方案,例如:'void parseLine(string (&allLines)[lines_count], int lines_count2, string line)' 但它们没有用
猜你喜欢
  • 2018-09-01
  • 2014-08-11
  • 2017-07-25
  • 2016-07-05
  • 1970-01-01
  • 2011-07-08
  • 2010-12-24
  • 2016-02-28
  • 2018-06-30
相关资源
最近更新 更多