Reputation: 1647
I have following C++ code that is supposed to read from this file . I want to capture the IP and PORT from the text file and write it into a file. I have done following code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("myfile.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout<<line;
if(line.find("IP")){
cout<<line;
}
if(line.find("PORT")){
cout<<line;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
But I am not getting correct output. What am I doing wrong here? I want to get those IP and PORT values and write another text file with following contents.
{
"ip":"127.0.0.1",
"port":"9999"
}
What should I be doing to achieve that?
Upvotes: 0
Views: 199
Reputation: 30489
It should be:
std::size_t loc = line.find("IP");
if(loc != std::string::npos) {
cout << line.substr(loc);
}
Do similar for the port also.
std::string::find returns the location of first character offset where the string was found or std::string::npos
if string is not found.
Upvotes: 1