0

I'm using the .find function to get a character position in order to do some string handling from lines which are read from a textfile. I feel that my implementation is correct but it gives me an unusable integer result. The #include <string> header is used, Code section is as follows:

ifstream IoTFile;
IoTFile.open("temp_data.txt");
if (IoTFile.is_open())
{
    while (!IoTFile.eof())
    {
        IoTFile >> sLine;
        int pos = sLine.find(",");
        cout << pos;
        //some irrelevant string handling...
    }
}

when I run the program, it does not give me any errors but the pos value is something like "1111111111111...." etc despite there being a "," comma at position 12. Any idea why this might be happening and how to solve it?

CoralK
  • 3,341
  • 2
  • 8
  • 21
OomBen
  • 19
  • 1

1 Answers1

2

There are a few issues with your code. Let me explain them one by one:

(1) find is more efficient when it looks for a char: Your code searches for a single comma character , so there is no need to pass a string as a parameter to the find() call. Using single quotes ',' instead of double quotes "," will make your code more efficient:

sLine.find(',');

(2) find doesn't return an int: The std::string::find() method returns a std::string::size_type value. So calling the find() method should be like this:

std::string::size_type pos = sLine.find(',');

or you can simply use the auto keyword and let the compile find the right type for you

auto pos = sLine.find(',');

(3) Check the result of find: After you call find() you have to check if it found anything. You can do this by comparing the result with the std::string::npos value. If the values are equal, then it didn't find anything.

std::string::size_type pos = sLine.find(',');
if (pos != std::string::npos) {
    std::cout << pos;
}

(4) Reading a file line by line: it seems to me that you want to read a file line by line, but what your code does is actually read it word by word. This is why your find() calls are not working properly. If you want to read the file line by line, you can do this:

std::ifstream file("temp_data.txt");
if (file.is_open()) {
    std::string line;
    while (getline(file, line)) {
        std::string::size_type pos = line.find(',');
        // only print pos if the comma was found
        if (pos != std::string::npos) {
            std::cout << line << " - pos = " << pos << '\n';
        }
    }
    file.close();
}
HugoTeixeira
  • 3,879
  • 2
  • 18
  • 28