Input:
10.0.0.5 127.0.0.1 3472
10.0.0.11 127.0.0.1 3000
10.0.0.12 127.0.0.1 3030
code:
struct sample{
string Neighbours;
} input;
int main()
{
string mytext;
int j=0;
ifstream MyReadFile("/f.txt");
while(getline(MyReadFile,mytext))
{
if(j%2==0)
{
input.Neighbours=mytext;
}
j ;
}
cout<<input.Neighbours<<endl;
MyReadFile.close();
}
I am able to get only the last value that is 10.0.0.12 127.0.0.1 3030 as output. what should I do to read all the data and store them into a variable???
CodePudding user response:
The most C way to read a whole file in at once is by using the <iterator>
library.
#include <iterator>
#include <string.h>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("input.txt", std::ios::in);
std::string str ((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
std::cout << str << "\n";
}
The output will just be the whole content of "input.txt".
Explanation: In this line
std::string str ((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
you are using the overloaded std::string
constructor to construct a string using a start- and end-iterator. std::istreambuf_iterator<char>(file)
returns an iterator to the beginning of file
, std::istreambuf_iterator<char>()
one to the end by using std::istreambuf_iterator<>()
's default return value.
CodePudding user response:
You only have the last value as output because you are assigning directly to the Neighbours
variable input.Neighbours = mytext
, you can replace code inside conditional if
by this way:
if(j%2==0)
{
input.Neighbours = mytext "\n";
}
j ;
The only thing it will do is store them in the variable, but you could also create a vector<string>
and then you would have better access to the text extracted from the file.
// print the content of a text file.
#include <iostream>
#include <fstream> // std::ifstream
#include <vector>
#include <string>
using namespace std;
struct sample {
vector<string> Neighbours;
} input;
int main () {
ifstream file("test.txt");
string myText;
int j=0;
while (getline(file, myText))
{
if (j%2==0)
{
input.Neighbours.push_back(myText);
}
j ;
}
for (auto &neighbour: input.Neighbours) cout << neighbour << endl;
return 0;
}
...
10.0.0.5 127.0.0.1 3472
10.0.0.11 127.0.0.1 3000
10.0.0.12 127.0.0.1 3030