2011-06-06 111 views
1

我试图使用string :: find方法来确定字符串“hello”(带有空格之前和之后)是否存在于.txt文件的一行中。如果是这样,它应该打印出行号(位置不重要)。问题是,它没有找到字符串。请帮忙。string :: find找不到匹配

int main() { 
    string key (" hello "); 
    ifstream myReadFile; 
    myReadFile.open("test.txt"); 
    string s; 
    int lineCount = 1; 
    int found; 
    if (myReadFile.is_open()) { 
     while (!myReadFile.eof()) { 
      getline(myReadFile, s); 
      found = s.find(key); 
      if(found != string::npos) { 
       cout<<lineCount<<endl; 
       lineCount++; 
      } 
     } 
    } 
    myReadFile.close(); 
    return 0; 
} 
+0

运行它在调试器中,看看它出错的地方。 – 2011-06-06 02:59:54

+0

注意:'string :: find()'不会**返回一个'int'。请使用std :: string :: size_type。 – 2011-06-06 03:20:27

+0

Martin:虽然我更喜欢这种结构,但OP的程序实际上并没有错误地处理最后一行;如果你尝试在最后一行之后读取一行,getline将清除字符串。所以总是有一个额外的循环,'s'是空的,但这不会使输出错误。 – 2011-06-06 03:21:00

回答

0

似乎怎么做,你有它只是计算的是在他们这个字符串的行数。您应该在循环的每次迭代中增加行号var,而不仅仅是在找到字符串时。

int main() { 
    std::string key (" hello "); 
    ifstream myReadFile; 
    myReadFile.open("test.txt"); 


    if (myReadFile) { 

     std::string line; 
     int line_number = 0; 
     while (std::getline(myReadFile, line)) { 
      line_number++;     
      if (line.find(key) != std::string::npos) 
       std::cout << line_number << std::endl; 
     } 

    } else { 
     std::cout << "Error opening file\n"; 
    } 
} 
+0

看不到'if(myReadFile)'的用法' – 2011-06-06 03:21:26

0

int found应该是string::size_type。这可能是你的问题,因为int是有符号的而size_t是无符号的。有关更多信息,请参阅string::npos

非营利组织是一个静态成员恒定值 与 size_t类型的元素的最大可能值。

编辑:

感谢Martin的评论我换成size_tstring::size_type

+0

啊谢谢,我已经这样做了,那么我必须解决另一个问题,并忘记改变它。 – Matt 2011-06-06 03:03:01

+0

根据我的标准npos(和查找)副本有std :: string :: size_type类型std :: string :: size_type – 2011-06-06 03:24:18

+0

@Martin:这很奇怪我一直用它作为size_t – GWW 2011-06-06 03:25:35

2

如果您所看到的问题是,你的程序总是打印1,2,3,......而不是正确的行号,那是因为你只增加lineCount如果子被发现;修复它将lineCount++移至if(found != string::npos)区块之后。

如果根本没有看到任何输出,则该文件不包含" hello "(大小写很重要,而且这些空格字符不会与其他空白字符匹配),或者“test.txt”不在其中正确的地方或名称错误。

注:foundstring::npos之间的比较是确定在这里(尽管一个是签署int,另一个是size_t(可能是64位系统上unsigned int或可能unsigned long long),有趣的是,这将打破,如果你。将found更改为unsigned intsize_t恰好是更宽的无符号类型(在32位计算机上,您可以通过使foundunsigned short来模拟此情况)。由于您实际上未使用found的值,因此最好完全避免转换,只是做if (s.find(key) != string::npos)