开发者

string::find is not finding match

Im trying to use the string::find method to determine if the string " hello " (with space before and after) exists in a line of a .txt file. if it does, its supposed to print out the line number(position isnt important). the problem is, its not finding the string. please help.

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++;开发者_C百科
            }
         }
    }
    myReadFile.close();
    return 0;
}


If the problem you're seeing is that your program always prints 1, 2, 3, ... instead of the correct line numbers, it's because you only increment lineCount if the substring was found; to fix it move lineCount++ to after the if(found != string::npos) block.

If you're not seeing any output at all, either the file doesn't contain " hello " (case matters, and also those space characters won't match other whitespace) or "test.txt" isn't in the right place or has the wrong name.

NOTE: The comparison between found and string::npos is OK here (even though one is a signed int and the other is a size_t (probably unsigned int or possibly unsigned long long on a 64-bit system). Interestingly, it will break if you change found to an unsigned int and size_t happens to be a wider unsigned type (on a 32-bit machine, you can simulate this situation by making found an unsigned short). Since you don't actually use the value of found, it's probably best to avoid conversions altogether and just do if (s.find(key) != string::npos).


What it seems to be doing as you have it is just counting the number of lines that have that string in them. You should increment the line number var in every iteration of the loop, not just when the string is found.

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";
    }
}


int found should be string::size_type. This may be your issue since int is signed and size_t is unsigned. See string::npos for more info.

npos is a static member constant value with the greatest possible value for an element of type size_t.

EDIT:

Thanks to Martin's comments I replaced size_t with string::size_type

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜