Want to read integer from a textfile - c++

So my problem is, when i read the file the "ki" , "kivel" and the "meddig" variables are good, but the "mettol" variable seems like it is disappeared.
struct Haboru {
string ki;
string kivel;
int mettol;
int meddig;
};
int main()
{
Haboru haboruk[10];
int k = 0;
ifstream haboru;
haboru.open("haboruk.txt");
// The rows are in "haboruk.txt" like these:
// Xhosa Zulu 1696 1736
// Zulu Ndebele 1752 1782
// Zulu Sotho 1756 1772
while(!haboru.eof())
{
haboru >> haboruk[k].ki >> haboruk[k].kivel >> haboruk[k].mettol >> haboruk[k].meddig;
k++;
}
}
The output is this:

Using !file.eof() as a condition to extract is not correct. You have to perform the extraction, and then check if the file is valid. But even using !file.eof() afterwards is still not correct:
Let's make this simpler by creating an inserter for a Haboru object:
std::istream& operator>>(std::istream& is, Haboru& haboruk)
{
if (!is.good())
return is;
is >> haboruk.ki;
is >> haboruk.kivel;
is >> haboruk.mettol >> haboruk.meddig;
return is;
}
Then you can create your vector (or std::array C++11) and use the inserter for each element:
std::vector<Haboru> haboruks;
Haboru haboruk;
while (haboru >> haboruk)
{
haboruks.push_back(haboruk);
}
Or...
std::vector<Haboru> haboruks((std::istream_iterator<Haboru>(haboru)),
std::istream_iterator<Haboru>());

Related

How to use getline() with multiple variables in the same line?

I'm trying to read each line from a file and store the data in each line. Say the line is "x y z". What arguments should the getline function use in order to read and store x, y and z individually?
void readData(Gene *data, int num)
{
int codeNum;
int i = 0;
int k = num;
ifstream inputFile;
inputFile.open("example.data");
inputFile >> codeNum;
while(i < k){
getline(inputFile, data[i].geneCode, data[i].MutCode[0],
data[i].MutCost[0], data[i].MutCode[1],
data[i].MutCost[1]);
i++;
}
This is what I have. Note that all the vars I'm trying to read are strings, and that k is the total number of lines. when trying to compile I get an error saying "no matching function to call to getline()" and something about "candidate function template not viable". Any idea what I'm doing wrong?
I highly recommend you use a vector of structures (or classes) rather than multiple, parallel arrays.
struct Mutation_Code_Cost
{
Mutation_Code_Type MutCode;
Mutation_Cost_Type MutCost;
};
struct Gene
{
Gene_Code_Type geneCode;
Mutation_Code_Cost mutation_info[2];
};
You can then overload operator>> to read in the structures from a text stream:
struct Mutation_Code_Cost
{
Mutation_Code_Type MutCode;
Mutation_Cost_Type MutCost;
friend std::istream& operator>>(std::istream& input, Mutation_Code_Cost& mcc);
};
std::istream& operator>>(std::istream& input, Mutation_Code_Cost& mcc)
{
input >> mcc.MutCode;
input >> mcc.MutCost;
return input;
}
struct Gene
{
Gene_Code_Type geneCode;
Mutation_Code_Cost mutation_info[2];
friend std::istream& operator>>(std::istream& input, Gene& g);
};
std::istream& operator>>(std::istream& input, Gene& g)
{
input >> g.geneCode;
input >> g.mutation_info[0];
input >> g.mutation_info[1];
return input;
}
You can the read from the file like so:
std::vector<Gene> database;
Gene g;
std::string record;
while (std::getline(input_file, record))
{
std::istringstream record_stream(record);
if (record >> g)
{
database.push_back(g);
}
}

Find number of items in .txt file

I'm looking for a way to find the number of items in a .txt file.
The file structure is as follows:
students.txt pricem 1441912123
house.pdf jatkins 1442000124
users.txt kevin_tomlinson 1442001032
accounts.mdb kevin_tomlinson 1442210121
vacation.jpg smitty83 1442300125
calendar.cpp burtons 1442588012
The result should be 18 in this example since there are 18 separate "words" in this file.
I need that value so I can iterate through the items and assign them to an array of structures (maybe there's a way to accomplish both of these steps together?):
// my structure
struct AccessRecord
{
string filename;
string username;
long timestamp;
};
// new instance of AccessRecord
// max possible records: 500
AccessRecord logRecords[500];
// while file has content
while (!fin.eof())
{
// loop through file until end
// max possible records: 500
for (int i = 0; i < 500; i++) // need to figure out how to iterate
{
fin >> logRecords[i].filename
>> logRecords[i].username
>> logRecords[i].timestamp;
}
}
Which will then be written to the screen.
So the question is, how do I find the count? Or is there a better way?
You know that each line contains a string, a string and a long, so you can iterate with:
std::vector<AccessRecord> logs;
std::string fname, uname;
long tstamp;
while(fin >> fname >> uname >> tstamp) {
logs.push_back(AccessRecord(fname, uname, tstamp));
//To avoid copies, use: (thanks #Rakete1111!)
//logs.emplace_back(std::move(fname), std::move(uname), tstamp);
}
This is assuming you've created a constructor for your struct like:
AccessRecord(std::string f, std::string u, long t)
: filename(f), username(u), timestamp(t) { }
Notice that I'm using an std::vector here instead of an array so that we don't even have to worry about the number of items, since the vector will resize itself dynamically!
You should overload operator>> for your structure:
struct AccessRecord
{
string filename;
string username;
long timestamp;
friend std::istream& operator>>(std::istream& input, AccessRecord& ar);
};
std::istream& operator>>(std::istream& input, AccessRecord& ar)
{
input >> ar.filename;
input >> ar.username;
input >> ar.timestamp;
return input;
}
This allows you to simplify your input function:
AccessRecord ar;
std::vector<AccessRecord> logs;
//...
while (fin >> ar)
{
database.push_back(ar);
}
Usually, if you are accessing an objects data members directly outside of the class or structure, something is wrong. Search the internet for "data hiding", "c++ encapsulation" and "c++ loose coupling".

How to assign each row of a text file to a new vector?

I am C++ noob, I have a text file with 4 rows and 3 columns, where each row corresponds to a sensor signal. How do I load each row to a separate vector<float>?
(0.165334,0) (0.166524,-0.0136064) (-0.144899,0.0207161)
(0.205171,0) (0.205084,-0.0139042) (-0.205263,0.0262445)
(0.216684,0) (0.215388,-0.0131107) (-0.193696,0.0251303)
(0.220137,0) (0.218849,-0.0135667) (-0.194153,0.025175)
This is what I have so far, but this code loads data as string. I want to load my final data as vector<vector<float>>?
vector<vector<string> > input;
ifstream fileFFT(Filename.c_str());
string line;
while(getline(fileFFT, line)){
if(line.empty()){
continue;
}
stringstream row(line);
vector<string> values((istream_iterator<string>(row)),(istream_iterator<string>())); //end
input.push_back(values);
}
Here's something to get you started:
class Point
{
public:
double x;
double y;
friend std::istream& operator>>(std::istream& input, Point& p);
};
std::istream& operator>>(std::istream& input, Point& p)
{
char c;
input >> c; // Read open parenthesis
input >> p.x;
input >> c; // Read comma
input >> p.y;
input >> c; // Read closing parenthesis
return input;
};
//...
std::string row_text;
std::vector<std::vector<Point>> matrix;
while (std::getline(my_file, row_text))
{
std::vector<Point> row;
std::istringstream(row_text);
Point p;
while (row_text >> p)
{
row.push_back(p);
}
matrix.push_back(row);
}
I've created a Point class to represent the pair of floating point numbers.
I also overloaded operator>> to make reading a Point easier.
The loop reads one record or text line, then creates a vector of Point from the text line.
The record or row is then appended to the matrix.
You have half the answer already - use std::getline() to read each line, and then use std::(i)stringstream to process each line.
Now, what you are missing is the other half - parsing each line. And since you already know how to use std::istream_iterator, I would do something like this:
typedef std::pair<float, float> SensorValue;
typedef std::vector<SensorValue> SensorValues;
std::istream& operator>>(std::istream &in, SensorValue &out)
{
float f1, f2;
char ch1, ch2, ch3;
if (in >> ch1 >> f1 >> ch2 >> f2 >> ch3)
{
if ((ch1 == '(') && (ch2 == ',') && (ch3 == ')'))
out = std::make_pair(f1, f2);
else
in.setstate(std::ios_base::failbit);
}
return in;
}
...
std::vector<SensorValues> input;
std::ifstream fileFFT(Filename.c_str());
std::string line;
while (std::getline(fileFFT, line))
{
if (line.empty())
continue;
std::istringstream row(line);
SensorValues values;
std::copy(std::istream_iterator<SensorValue>(row), std::istream_iterator<SensorValue>(), std::back_inserter(values));
input.push_back(values);
}

Reading from file into a vector

I'm using C++ and I'm reading from a file lines like this:
D x1 x2 x3 y1
My code has:
struct gate {
char name;
vector <string> inputs;
string output;
};
In the main function:
vector <gate> eco;
int c=0;
int n=0;
int x = line.length();
while(netlist[c][0])
{
eco.push_back(gate());
eco[n].name = netlist[c][0];
eco[n].output[0] = netlist[c][x-2];
eco[n].output[1] = netlist[c][x-1];
}
where netlist is a 2D array I have copied the file into.
I need help to loop over the inputs and save them in the vector eco.
I don’t fully understand the sense of the 2D array but I suspect it’s redundant. You should use this code:
ifstream somefile(path);
vector<gate> eco;
gate g;
while (somefile >> g)
eco.push_back(g);
// or, simpler, requiring #include <iterator>
vector<gate> eco(std::istream_iterator<gate>(somefile),
std::istream_iterator<gate>());
And overload operator >> appropriately for your type gate:
std::istream& operator >>(std::istream& in, gate& value) {
// Error checking … return as soon as a failure is encountered.
if (not (in >> gate.name))
return in;
gate.inputs.resize(3);
return in >> gate.inputs[0] >>
gate.inputs[1] >>
gate.inputs[2] >>
gate.output;
}

Overload stream operator for nested template C++ STL

I've got a data file that is a single line consisting of a nested series of doubles eg.
[[0.127279,0.763675,0.636396],[0.254558,0.890955,0.636396],
[0.127279,0.636396,0.763675],[0.254558,0.763675,0.763675],
[0.381838,0.890955,0.763675],[0.127279,0.509117,0.890955],
[0.254558,0.636396,0.890955],[0.509117,0.890955,0.890955]]
I'd like to be able to read this into a STL vector<vector<double> > using the stream operator which is templated across the inner type of A:
vector<vector<double> > A;
FIN >> A;
I've figured out a way to do this when the vector is not nested, ie. a simple vector<T> as so:
template <class T>
istream& operator>>(istream& s, vector<T> &A){
T x;
string token; char blank;
s >> blank; // Gobble the first '['
while( getline(s, token, ',') ) {
istringstream input(token);
input >> x;
A.push_back(x);
}
s >> blank; // Gobble the last ']'
return s;
}
But I'm having problem with the istream& operator>>(istream& s, vector<vector<T> >&A) part as I can't seem to catch the inner ]'s properly. I'm sure that Boost has a way of doing this, but I'd like to see a solution with the STL for pedagogical purposes.
Note: I'm aware that overloading the stream operator for vector<T> can have far-reaching undesirable consequences and that the implementation should be wrapped up in its own class - I'm using this example above as it stands to clarify the question.
EDIT:
I'd like the method to be robust enough to handle a input array whose size (and inner array) size is not known in advance, but inferred from reading the stream.
Actually, the problem with your code that you want to use the same function for both, when T is:
vector<double>
double
But the logic which needs to read the data into vector and double is slightly different. So you cannot do that, at least not with that simple logic:
I would prefer to write two functions, to handle both cases separately. After all, even in your case, the compiler will generate two different functions for each value of T.
template <class T>
istream& operator>>(istream& s, vector<T> &A)
{
T x;
string token; char blank;
s >> blank; // Gobble the first '['
while( getline(s, token, ',') )
{
istringstream input(token);
input >> x;
A.push_back(x);
}
// s >> blank; // Gobble the last ']'
return s;
}
template <class T>
istream& operator>>(istream& s, vector<vector<T>> &A)
{
vector<T> x;
string token;
char blank;
s >> blank; // Gobble the first '['
while( getline(s, token, ']') )
{
istringstream input(token);
input >> x;
s >> blank; //read , after [...]
A.push_back(x);
x.clear();
}
s >> blank; // Gobble the last ']'
return s;
}
Test code:
int main() {
vector<vector<double>> A;
cin >> A;
for(size_t i = 0 ;i < A.size(); ++i)
{
for(size_t j = 0 ; j < A[i].size(); ++j)
cout << A[i][j] <<" ";
cout << endl;
}
return 0;
}
Input:
[[1,2,3],[4,5,6],
[7,8,9],[10,11,12],
[13,14,15],[16,17,18],
[19,20,21],[22,23,24]]
Output:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
22 23 24
Online demo : http://ideone.com/iBbmw
In your particular example which is very simple.
Read the whole line into a string.
Replace all [ , ] and , with whitespace character.
Create a simple stringstream with whitespace replaced string.
Now you can have a a simple loop of
double x;
while( stringstreamp >> x )
{
}
And some special logic after reading three doubles to insert them them into a new array.
Some years later, and I was here struggling with the same problem.
Based on your contribution, I developed a modified version of the original template. This one is able to parse multidimensional arrays, even if they are spread across several lines.
template <class T>
istream& operator>>(istream& s, vector<T> &A){
while(true){
T x;
char c = s.peek();
if( c == '[' || c == ','){
s.ignore();
if(s >> x) A.push_back(x);
else throw invalid_argument("Bad, bad JS array!");
continue;
}
if( c == ']') {
s.ignore();
return s;
}
/* Ignore line-break */
s.ignore();
}
return s;
}
Hope this can be useful for someone.