I have a text file of NFL teams. I am having a problem when parsing through the string when it comes to teams with 2 names and not one. (i.e. New England and Pittsburgh) the next item in the file is an int. I also have to read these values into a linked list.
infile >> t.date // t is a team struct which contains char name and ints
>> t.name
>> t.W
>> t.L
>> t.T
Can I just use an if else statement between the name and Wins to check if the next char is a char? And then if it is a char it could just save the next word, "England" for the second half of New England's name in the same name field, and if its an int it will move on to the Wins field.
txt file ex
New England 2 4 0
Pittsburgh 1 6 0
the code above was what I was trying to use to assign the name to the team struct
struct team
{
public:
team& do_input(std::istream& is);
std::string date, name, name2;
int wins,
losses,
ties;
std::string perc,
home,
road,
div,
conf;
int league;
};
infile >>t.date;
while (infile >> t)
{
t.do_input(infile) ;
//cout << t.date << t.name;
L.push_back(t);
t.name2 = " ";
}
Let's start by maintaining your code. The first thing I would do is create an overload of operator >> that takes an input stream and a team object.
std::istream& operator >>(std::istream& is, team& t);
This function should delegate the operation of extracting the input to a method called do_input():
std::istream& operator >>(std::istream& is, team& t)
{
if (is.good())
t.do_input(is);
return is;
}
do_input should read objects of type char into the respective string objects in your team class. Speaking of your team class, it's much better to use std::string for representation of string values:
struct team
{
...
std::string date;
std::string name;
int W, L, T;
};
This way the string can be as large enough as we need it. We no longer have to worry about a potential buffer overflow (i.e reading a string larger than 10 bytes). We can also use the convenient methods that std::string provides.
It's further recommended that you use good variable names so that maintainers of your code can know at a glance what it means. For instance, try these:
int wins, losses, ties;
Now it is clear to me (and to others) what these names imply.
So team::do_input is a member function that reads in the strings and integers from the file to the data members of the instance from which it is being called. Here's a full implementation:
struct team
{
public:
team& do_input(std::istream&);
private:
std::string date, name;
int wins, losses, ties;
};
team& team::do_input(std::istream& is)
{
std::getline((is >> date).ignore(), name);
is >> wins >> losses >> ties;
return *this;
}
Error reporting has been left out to keep the example concise. I hope this helped.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Im trying to read from a file called stock.txt, which contains the following values:
ID, Item, Colour, Size, Quantity, Price
11,T-shirt,blue,XL,2,10.500000
12,Supreme,red,M,10,20.500000
13,BANG,red,M,10,20.500000
I wanted to store each item in a list, how can I do that?
int main() {
ifstream infile;
infile.open("Stock.txt");
string id; string title; string colour; string size; string quantity; string cost;
//If file open is successful
while(infile.good()){
getline(infile,id,',');
getline(infile,title,',');
getline(infile,colour,',');
getline(infile,size,',');
getline(infile,quantity,',');
getline(infile,cost,'\n');
}
infile.close();
}
You should use a more moden C++ approach.
I would be happy, if you could study this solution and try to use some features in the future.
In the object orient world, we use classes (or structs) and put data and functions, operating on this data, in one (encapsulated) object.
Only the class should know, how to read and write its data. Not some outside global functions. Therefor I added 2 member functions to your struct. I have overwritten the inserter and the extractor operator.
And in the extractor, we will use modern C++ algorithms, to split a string into tokens. For this purpose, we have the std::sregex_token_iterator. And because there is a specialized function for this purpose, we should use it. And besides, it is ultra simple.
With the below one-liner, we split the complete string into tokens and put the resulting tokens in a std::vector
std::vector token(std::sregex_token_iterator(line.begin(), line.end(), delimiter, -1), {});
Then we copy the resulting data in our member variables.
For demo output I have also overwritten the inserter operator. Now you can use the exteractor and inserter operators (">>" and "<<") for variables of type Stock, as for any other C++ integral variable.
In main, we use also an ultrasimple approach. First, we open the file and check, if this was OK.
Then we define a variable "stocks" (A std::vector of Stock) and use its range constructor and the std::istream_operator to read the complete file. And, since the App has an overwritten extractor operator, it knows, how to read and will parse the complete CSV file for us.
Again, the very simple and short one-liner
std::vector stocks(std::istream_iterator<Stock>(inFile), {});
will read the complete source file, all lines, parse the lines and store the member variables in the single stock elements of the resulting std::vector.
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <regex>
#include <iterator>
#include <algorithm>
std::regex delimiter{ "," };
struct Stock {
// The data. Member variables
std::string id{};
std::string title{};
std::string colour{};
std::string size{};
std::string quantity{};
std::string cost{};
// Overwrite extractor operator
friend std::istream& operator >> (std::istream& is, Stock& s) {
// Read a complete line
if (std::string line{}; std::getline(is, line)) {
// Tokenize it
std::vector token(std::sregex_token_iterator(line.begin(), line.end(), delimiter, -1), {});
// If we read at least 6 tokens then assign the values to our struct
if (6U <= token.size()) {
// Now copy the data from the vector to our members
s.id = token[0];
s.title = token[1];
s.colour = token[2];
s.size = token[3];
s.quantity = token[4];
s.cost = token[5];
}
}
return is;
}
// Overwrite inserter operator
friend std::ostream& operator << (std::ostream& os, const Stock& s) {
return os << "ID: " << s.id << "\nTitle: " << s.colour
<< "\nSize: " << s.size << "\nQuantity: " << s.quantity << "\nCost: " << s.cost;
}
};
int main() {
// Open file and check, if it could be opened
if (std::ifstream inFile("stock.txt"); inFile) {
// Define the variable and use range constructor to read and parse the complete file
std::vector stocks(std::istream_iterator<Stock>(inFile), {});
// Show result to the user
std::copy(stocks.begin(), stocks.end(), std::ostream_iterator<Stock>(std::cout, "\n"));
}
return 0;
}
Please note: I am using C++17 and can define the std::vector without template argument. The compiler can deduce the argument from the given function parameters. This feature is called CTAD ("class template argument deduction").
Additionally, you can see that I do not use the "end()"-iterator explicitely.
This iterator will be constructed from the empty brace-enclosed initializer list with the correct type, because it will be deduced to be the same as the type of the first argument due to the std::vector constructor requiring that.
You should model each row with a class or struct:
struct Record
{
int id;
std::string title;
std::string colour;
std::string size;
int quantity;
double price;
friend std::istream& operator>>(std::istream& input, Record & r);
};
std::istream& operator>>(std::istream& input, Record & r)
{
char comma;
input >> r.id;
input >> comma;
std::getline(input, r.title, ',');
std::getline(input, r.colour, ',');
std::getline(input, r.size, ',');
input >> r.quantity;
input >> comma;
input >> r.price;
input.ignore(100000, '\n');
return input;
}
Now you can read into a list:
std::list<Record> database;
Record r;
while (infile >> r)
{
database.push_back(r);
}
The overloading of operator>> makes the code simpler and easier to read.
I'm trying to get inputs from a file by overloading the istream operator. For that, I declared it as friend of a class. Then, I take as input that same class like this:
file >> *(class pointer);
When I'm trying to debug the part of my code that need this to work, it goes as expected into this:
istream& operator>> (istream& in, MYCLASS& n)
{
string buffer;
while (!in.eof()) { // input is a file
in >> buffer;
// do stuff
}
return in;
}
The problem is that the buffer stays empty ("") and does not take what it's suppose to be taking from the file. Normally, the format of the file should not be a problem since I'm using a similar method elsewhere in my code without a problem, but here it is in case:
* Name Age
* Name Age
* Name Age
...
What should I put inside my istream overload function so i get inputs as intended?
This...
while (!in.eof()) {
...is broken. You should attempt to read and parse data into your variables, then check for failure/eof. Do not assume that you'll necessarily be at the end of file after reading the last MYCLASS. Instead:
string name;
int age;
while (in >> name >> age)
...do stuff...
If you've really got some kind of leading dot on each line, add a char and read into it too:
char dot;
string name;
int age;
while (in >> dot && dot == '.' && in >> name >> age)
...do stuff...
More generally, it's not a very scalable model to assume the rest of the input stream will contain one MYCLASS object. You could instead have a delimiter (e.g. when the first word on a line is not a name, but <END>), that terminates the loop.
Book.h:
#ifndef BOOKDATE
#define BOOKDATE
#include <iostream>
#include <string>
class Book{
friend std::istream& operator>>(std::istream&, Book&);
private:
std::string title, author;
int number;
};
std::istream& operator>>(std::istream&, Book&);
#endif // BOOKDATE
Book.cpp:
#include "BookDate.h"
using namespace std;
istream& operator>>(istream& is, Book& rhs){
getline(is, rhs.title);
getline(is, rhs.author);
is >> rhs.number;
if(!is)
rhs = Book();
return is;
}
I was wondering how exactly I should approach creating the input operator for the Book class. The title and author will be more than one word, so it fits that I need to use getline to receive that data. The issue then with getline is that it may pick up any '\n' left in the stream since cin was last used. For instance;
int x;
cin >> x; //newline is not extracted and left behind
Book a;
cin >> a; //"title" is automatically made empty!
I could instead use cin.ignore(256, '\n') but whose responsibility, the user's or class author's, is it to use this? Does the user use .ignore before he inputs a Book object or does the class author put .ignore at the beginning of the input operation?
It seems that in the former case the user would have to understand an .ignore method is needed but in doing so has to understand the implementation of the Book's input operator, which is not desirable. In the latter case, putting .ignore in the operator means my operator may not adapt to certain circumstances, since it always expects to encounter a newline before processing. For instance reading from an input file with data such as:
book1
author1
1
book2
author2
2
Means book1 gets ignored by cin.ignore(256,'\n').
To make your operator>> behave more like the operators for the built in types, you can use the ws manipulator to skip whitespace before you read your input.
Just use
is >> ws;
at the beginning of your input operator, and the stream will be positioned at the first non-whitespace character after the current position.
To overload the extraction operator properly you can change your input format to be a sequence of three variables that you want to populate, namely:
(title, author, number)
and modify your operator>> to:
istream& operator>>(istream& is, Book& rhs){
// just a suggestion: it is better if there is no input to do nothing
if(!is) return is;
string title, author;
int number;
char par1, comma, par2;
cin >> skipws >> par1 >> title >> comma >> author>> comma >> number >> par2;
if (par1 != '(' || comma != ',' || par1 != ')'){
// set failbit to indicate invalid input format
is.clear(ios_base::failbit);
}
rhs(title, author, number);
return is;
}
put is.ignore(); before getline(is, rhs.title);
I am trying to finish my lab, however I don't know how to allocate memory to a string. So I keep getting the error
warning: ‘_name’ is used uninitialized in this function [-Wuninitialized]
I don't also understand if my getline line is correct.
std::istream& operator>>(std::istream& is, Grade& RO){
int _mark;
char* _name;
std::cout<<"Subject name: ";
is.ignore();
is.getline(_name, (strlen(_name) + 1));
std::cout<<"Mark :";
is>> _mark;
RO=Grade(_name, _mark);
return is;
}
Ok #Jessica, (to general question and few info) I guess,
Grade is a class with two data members: int mark and string name. And you want to overload the insertion operator >> to populate these values.
(I recommend you leave all the cout expression outside this function). Here is one possible implementation:
istream& operator>> (istream& is, Grade& RO){
// declare local variables to insert the input values
int mark;
string name;
// extract values from input stream
is >> mark >> name;
// assuming you have member functions that set values for the object RO
RO.set_mark(mark);
RO.set_name(name);
return is;
}
I assigned myself some homework over the summer, and the project I am 98% finished with has come to a standstill due to this one problem.
I have a class called Mixed. It contains member data for a whole number, a numerator, and a denominator. I need to overload all of the common operators to allow multiplication, addition, comparison and streaming of objects of type Mixed. I have all the operators overloaded except for >> (the extraction operator).
All mixed numbers read in will be of format:
whole numerator/denominator
ex: 1 2/3, 0 7/8, -3 18/5, 0 -1/89
Header: friend istream& operator>> (istream &, Mixed);
CPP file: istream& operator>> (istream &in, Mixed m) {...}
For the assignment, I am limited to the iostream and iomanip libraries. My plan was to read in the values from the stream and assign them to temporary int variables (w, n, d) which I would then use with the Mixed constructor to create object m. Unfortunately, I cannot think of a way to separate the numerator and denominator. They are both ints, but they have a char (/) between them.
I cannot use getline() with its delimiter, because it assigns data to a char array, which I do not believe I can convert to an int without another library.
I cannot use a char array and then segment it for the same reason.
I cannot use a while loop with get() and peek() because, again, I do not think I will be able to convert a char array into an int.
I cannot use a string or c-string and then segment it because that requires external libraries.
Once again, I need to split a value like "22/34" into 22 and 34, using only iostream and iomanip. Is there some fairly obvious method I am overlooking? Is there a way to implicitly convert using pointers?
You could first extract the nominator, then the separating character, and then the denominator.
Example for illustration:
istream& operator>> (istream &in, Mixed &m) {
int num, denom;
char separ;
in >> num;
in.get(separ);
if (separ != '/')
in.setstate(ios::failbit);
in >> denom;
if (in) {
// All extraction worked
m.numerator = num;
m.denominator = denom;
}
return in;
}
Once again, I need to split a value like "22/34" into 22 and 34, using
only iostream and iomanip.
Couldn't you just read in the first integer, use get to get the next character, and then read the second integer? Something like this:
#include <iostream>
int main() {
using std::cin;
using std::cout;
int num;
int den;
while(cin) {
cin >> num;
if (cin.get() != '/') {
// handle error
}
cin >> den;
cout << num << "/" << den << std::endl;
}
return 0;
}
You can then make sure that the character read between the two integers was a '/' and handle appropriately if it isn't.