Trouble using the .find string function

I'm trying to find the word "language" in my text file (after that I'll have to do some further processing) but right now my console window displays "found" every other word

1
2
3
4
5
6
7
8
9
10
11
12
  int main() {
	string raw, headL[2], lang[2];
	ifstream data("testsample.txt");
	while (data.good()) {
		data >> raw;
		if (raw.find("language")) { cout << "found"; }
		cout << raw;
	}
	

	return 0;
}


this is whats in the text file:
{
"count": 269290,
"items": [
{
"language": "en",
"created": "2013-12-02T22:01:37.000+01:00",
"geometry": {
"type": "Point",
"coordinates": [
9.24072841,
45.47024867
]
},
"timestamp": 1386018097,
"municipality": {
"name": "Milano",
"acheneID": "http://dandelion.eu/resource/2bf72cfc3857f470be5457dc4aa77e578889e32d"
},
"entities": [
"http://it.dbpedia.org/resource/Germania"
],
"user": "6b8878e9d8"
},
{
"language": "it",
"created": "2013-12-02T22:01:46.000+01:00",
"geometry": {
"type": "Point",
"coordinates": [
9.2231945,
45.48381701
]
},
"timestamp": 1386018106,
"municipality": {
"name": "Milano",
"acheneID": "http://dandelion.eu/resource/2bf72cfc3857f470be5457dc4aa77e578889e32d"
},
"entities": [],
Usually is 0 that is interpreted as 'false' and std::string.find() never returns 0.

What about a code like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>

int main()
{
    std::string raw, headL[2], lang[2];
    std::ifstream data("testsample.txt");
    while (data.good()) {
        data >> raw;
        if (raw.find("language") != std::string::npos) { std::cout << "found"; }
        std::cout << raw;
    }   

    return 0;
}


Or you could choose to take advantage of the stdd:getline() function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <iostream>

int main()
{
    std::string raw, headL[2], lang[2];
    std::ifstream data("testsample.txt");
    
    while (std::getline(data, raw)) {
        if (raw.find("language") != std::string::npos) {
         std::cout << "found: "; 
     }
        std::cout << raw << std::endl;
    }
    

    return 0;
}


Good luck with your code!
Usually is 0 that is interpreted as 'false' and std::string.find() never returns 0.

Actually it can return zero, but only if the "to find string" occurs at the first element of the string. Ie:

1
2
3
4
5
6
7
8
9
10
11
#include <string>
#include <iostream>

int main()
{
    string raw{"language test for language"};

    std::cout << raw.find("language");

    return 0;
}


But if the find fails to find the string it returns std::string::npos, which is the largest possible value that can be held in a std::string::size_type, not zero as you have correctly pointed out.

Actually it can return zero, but only if the "to find string" occurs at the first element of the string

You are definitely right, jib.
Thanks a lot - I was giving a wrong answer.
Topic archived. No new replies allowed.