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();
}