C ++:在while循环中更新函数内部的变量值

时间:2015-05-07 01:47:49

标签: c++11 while-loop self-modifying

我不太擅长C ++,我正在编写一个程序来读取一行html文件中的多个URL,所以我写了这段代码:

ifstream bf;
short chapters=0;
string blkhtml;
string blktmpfile; //given
string urldown;    //given
size_t found = 0, limit;

    while(getline(bf, blkhtml)){
            while((blkhtml.find(urldown, found) != string::npos) == 1){
                found = blkhtml.find(urldown);
                limit = blkhtml.find("\"", found);
                found=limit + 1;
                chapters++;
            }
    }

我的问题是找不到更新以在while条件中使用。正如我所见,除非另一个std :: string类(对于字符串,str.erase()更新它的值,否则std :: string类不会更新,但是(str.at( )='')没有),如果我想要"找到"我该怎么办?每次循环开始时更新,以及条件。

我想做的是:

  • 检查urldown给定字符串是否有重合的表达式。

  • 设置它的第一个和最后一个字符。

  • 更新' pos'在找到url后的循环中,然后查找下一个。

我在cplusplus.com和cppreference.com上闲逛,但我找不到能帮助我的东西。

我想到一个循环上的std :: list :: remove,每个数字从0到9,然后给它一个新值,但我不知道它是否是最好的选择。

1 个答案:

答案 0 :(得分:1)

问题是你每次都从头开始搜索:

while((blkhtml.find(urldown, found) != string::npos) == 1){
    found = blkhtml.find(urldown); // Searches from beginning of the string

这应该是:

while((blkhtml.find(urldown, found) != string::npos) == 1){
    found = blkhtml.find(urldown, found); // Searches from "found"

或者,要只搜索一次,您可以将其放在while子句中:

while((found = blkhtml.find(urldown, found)) != string::npos){

此外,每次阅读新行时都不会重置found

while(getline(bf, blkhtml)){
    found = 0;