2017-10-20 50 views
-2

我正在使用在文件中搜索字符串(本例中为名称)的程序。我希望程序不要区分大小写,但strcmp是。我正在考虑将bot文件和用户输入转换为小写。但这样做效率不高。任何其他的建议来克服这一点?
这是代码的一小部分只得到程序在不使用strcmpi()的情况下使strcmp()不区分大小写()(C++)

cout << "\n Enter the Guests name: "; 
    cin.getline(look_4_person, 256); //name that is being looked up 
    cout << "\n Searching... \n"; 
    while(!name_file.eof()) 
    { 
     ++place; 
     name_file.getline(person,255); 
     if(strcmpi (person,look_4_person)==0) 
     { 
     found=place; 
     } 
    } 
    cout << "\n" << look_4_person << " is number " << found << 
      " on the list \n"; 
+3

这是可怕的风格和'while(!name_file.eof())'甚至是一个错误。你应该在一本好书中阅读现代C++。 –

+0

@BaummitAugen目前我正在使用Big C++(第二版) 你有什么建议吗? – Pouya

+3

https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

回答

2

在心里对BOT文件和用户输入转换为小写的想法。但这样做效率不高。任何其他的建议来克服这一点?

重新考虑这一点。

这是处理大小写敏感的典型方法。我的意思是将两个字符串(文件名和用户输入)转换为小写。

这需要O(n),其中n = max(filename.size, userInput.size)

至于性能,文件名和用户输入通常是微小的数据,因此,我敢肯定,将它们转换为小写,肯定会有是你的算法瓶颈

+0

但我不应该也小写文本文件以及? – Pouya

+0

是@Pouya,但它不会影响你的代码更复杂,请检查我更新的答案。 – gsamaras

0
while(!name_file.eof()){ 
     ++place; 
     name_file.getline(person,256); 
     for(i=0; i<200; i++) 
     { 
     person[i] = tolower(person[i]); //changes to lower case to compare 
     } 
     if(strcmp (person,look_4_person)==0){ //compares 
     found=place;        

     } 
相关问题