I wanted to know if it's possible to somehow determine if the line ends if im using something like fin >> something? Like in the code bellow, if the input file is ok, then everything is fine. But if somethings missing, it goes down. Like usualy it reads 3 variables from each line. But if there's variable missing in the line, i should know that. So i can read 3 variables from the next line etc. I dont really want to read symbol by symbol.
int main()
{
int ministrijas = 0;// Amount of roots
int Knot = 0;// Children ID
int Budget = 0; // children value
int Ministry = 0;// root ID
int Parent = 0;// Parent of the children
ifstream fin;
ofstream fout;
List h;
fin.open("budget.i1");
fout.open("budget.o1");
fin >> ministrijas;
for(int i=0; i < ministrijas; i++)
{
fin >> Knot >> Budget;
h.AddKnot(Ministry, Knot, Budget );
}
while(fin>>Parent>>Knot>>Budget)
{
h.AddKnot(Parent, Knot, Budget);
h.LinkKnots(Parent, Knot);
}
The input file looks like this:
1 //Defines the amount of roots
1 150 // Adds Root
1 11 30 // Then adds children to the root. 1 stands for the root ID, 11 is the id of the Children. 30 is the value of the children.
1 12 120
1 12 // Like here. The children is missing a value. Here's the problem.
11 111 10
11 112 20
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream inFile ( "test.txt" );
std::string line; // Stores each line from the txt file
std::istringstream iss;
int ministrijas , knot , budget , parent;
inFile >> ministrijas >> knot >> budget; // Read the first 2 lines from the file
std::cout << ministrijas << std::endl << knot << ' ' << budget << std::endl;
std::getline ( inFile , line ); // Store a line from the file in the string variable, line
// As long as a line can be read from the file
while ( std::getline ( inFile , line ) ) {
iss.str ( line ); // Set line as the content of iss
// If 3 variables can be read from iss
if ( iss >> parent >> knot >> budget )
std::cout << parent << ' ' << knot << ' ' << budget << std::endl;
else {
std::cout << "Less than 3 Variables on this Line ..." << std::endl;
iss.clear (); // Reset the bit of iss
}
}
return 0;
}
test.txt
1 2 3 4 5 6 7
1
1 150
1 11 30
1 12 120
1 12
11 111 10
11 112 2
Output
1 2 3 4 5 6 7 8 9 10
1
1 150
1 11 30
1 12 120
Less than 3 Variables on this Line ...
11 111 10
11 112 2
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
After the second line, the program starts reading line by line and store each line in iss. If the program cannot read 3 items from the iss, it prints "Less than 3 Variables on this Line ..." and continues on to the next line.