How can I handle the info I get from file while reading in c++? - c++

int i = 5;
char c = 'n';
string st = "cool";
ofstream my("we.txt");
my <<st<<","<<c<<","<<i<<","<<endl;
string s;
ifstream your("we.txt");
while(your){
getline(your, st, ',');
your>>c;
your.ignore(1);
your>>i;
your.ignore(1);
cout<<st<<","<<c<<","<<i<<endl;
}
my.close();
I don't even know what your.ignore(1) stands for, but somehow it works. The problem is that it print the result twice, why?
Can someone explain me how to handle the info that I've written in the file? If I wanted to save in a file 3 info string trade, double price and char sold (y/n), about every item I have how can I manage it?
It would look like this
Timberland, 40, n;
Gucci, 10, y; ..... etc..
I need it now, cause tomorrow I have a test, I appreciate your help, and sorry for my english!

As for the problem with the double-printing, it's because the eofbit flag is not set until after you read from beyond the end of the file. That means your loop will iterate once to many.
I suggest you instead use getline to read the complete line (in the condition of the loop), and then use e.g. std::istringstream to parse the line.
So do e.g.
while (std::getline(your, fullLine))
{
std::istringstream istr(fullLine);
getline(istr, st, ',');
istr >> c;
// etc.
}

Related

ifstream from next/new line in c++

I am having set of data stored in a file which are basically names. My task is to get all the first letters from each name. Here is the file:
Jack fisher
goldi jones
Kane Williamson
Steaven Smith
I want to take out just first word from each line(ex. jack, goldi, kane, Steaven)
I wrote following code for it, just to take take out 2 names. Here it is:
string first,last;
ifstream Name_file("names.txt");
Name_file>>first;
Name_file>>endl;
Name_file>>last;
cout<<first<<" "<<last;
it is giving error. If I remove endl, it takes the first full name(Jack, fisher) whereas I want it should take (jack ,goldi). How to do it ? Any idea? Thanks in advance for help.
Name_file>>endl; is always wrong.
Even then, you can't use >> like that, it will stop on a space, which is why when you remove endl you see the problem that first and last contain only the first line.
Use std::getline to loop over your file instead and get the full names, then split the line on the first space to get the first name:
ifstream Name_file("names.txt");
std::string line;
while (std::getline(Name_file, line))
{
std::string firstName = line.substr(0, line.find(' '));
//do stuff with firstName..
}
Though I don't mind "Hatted Rooster"implementation I think it can be a little less efficient when the input suddenly contains a very long line.
I would use ignore() to remove the rest of the line:
int main()
{
std::ifstream nameFile("names.txt");
std::string firstName;
while (nameFile >> firstName)
{
// You got a first name.
// Now dump the remaing part of the line.
nameFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
I hope this solves your query.
ifstream Name_file;
string line;
Name_file.open("names.txt");
if(Name_file.fail()){ cerr<<"Error opening file names.txt !!"<<endl;return;}
vector<string> v; // array to store file names;
while(Name_file >> line){
string word;
getline(Name_file, word);
v.push_back(line);
}
// printing the first names
for(int i = 0; i < v.size();i++){
cout<<v[i]<<endl;
}

Is there a way to extract certain info from a string? c++

I need to read in some lines from a text file (amount of lines will be known during run time) but an example could be something like this:
Forecast.txt:
Day 0:S
Day 3:W
Day 17:N
My idea was to create a class which I did:
class weather
{
int day;
char letter;
};
Then create a vector of class as so:
vector<wather>forecast;
and now here is where I'm stuck. So I think I'd use a while loop?
id use my ifstream to read the info in and use a string to hold the information im reading in.
What I want to do is read in each line and extract the day number so in this example the 0, 3 and 15 and get the letter so S, W, N and store it in the vector of the class.
I was wondering if there's any way to do that? I could be coming at this wrong so forgive me im new to c++ and trying to figure this out.
Thank you for helping!
Your can use std::istringstream to parse each line, eg:
#include <sstream>
while (getline(in_s1, lines2))
{
istringstream iss(lines2);
string ignore1; // "Day"
char ignore2; // ":"
forecast f;
if (iss >> ignore1 >> f.day >> ignore2 >> f.letter)
weather.push_back(f);
}
Live Demo
Alternatively, you can parse each line using std::regex and related classes.
istringstream and the >> operator is probably the neatest C++ way to do it, as described in Remy's answer. In case you prefer to be a little less reliant on the stream magic and a bit more explicit, you can find the tokens you need and then extract them directly from the string.
Something like this:
while (getline(in_s1, lines2))
{
size_t startPos = lines2.find(' '); //get position of the space before the day
size_t endPos = lines2.find(':', startPos); //get position of the colon after the day
string day = lines2.substr (startPos+1, endPos-startPos-1); //extract the day
forecast f;
f.day = stoi(day); //stoi only supported since C++11, otherwise use atoi
f.letter = lines2[endPos+1];
weather.push_back(f);
}

Issue reading multiple lines from .txt file in C++

I'm trying to create a student database system for a school project. I'm trying to create a function that will search a .txt file for the student id and return all of the other variables on the string. This is working great if I search for the id of the student on the first line of the txt file but isn't capturing anything if I search for a student on another line. Am I missing something obvious?
The student data is 16 strings delimited by commas on each line. The student ID is the first string.
Thanks for any assistance!
StudentType findStudent(int studentToFind)
{
ifstream inFile;
inFile.open("students.txt");
string currentLine;
string dataRead[16];
istringstream is;
int currentStudent;
if (inFile)
{
while (getline(inFile, currentLine))
{
is.str(currentLine);
for (int i = 0; i < 16; i++)
{
getline(is, dataRead[i], ',');
}
currentStudent = stoi(dataRead[0]);
if (currentStudent == studentToFind)
{
/*
Do stuff here
*/
inFile.close();
return foundStudent;
}
cin.ignore(); // Not sure if this is needed but I was trying to
// clear the \n char if that was causing the issue
}
}
}
First : you aren't using cin, so get rid of cin.ignore().
Second : you should make sure you ALWAYS close infile at the end... so I would suggest not returning early or closing early, but using a break statement to exit your loop and then have a single return of whether you found it or not.
Third: Now that you removed all the 'gorp' we can finally hone in on the problem ... effectively the question is do we read all the lines?
Well let's check that, try printing out currentLine each time at the beginning of the while loop, if you know currentLine is updated properly, is is getting updated each time? yes...
ok then look at your next loop let's print out currentStudent each time... does currentStudent print the right value for each line? i.e. is the getline write into dataRead[i] actually writing what you think it should be to the right space?
Did you find the problem yet?
This is the kind of problem you need to learn how to solve yourself using print statements and a debugger. That what its for. If you are in visual studio run in debug mode and step through it... if not, use gdb. learn it and get used to it, you'll be using it a lot!
good luck

Reading / Writing Files for a calculator: atof error

I currently have a text file that is as follows:
12 6 4 9
It is a very simple text file since I want to just get one line working and then maybe expand to multiple lines later. Extra aside: this is for a RPN calculator I am working on.
I want to go through this text file character by character. The way I currently have it implemented is with a simple while loop:
string line;
while (!infile.eof()){
getline(infile, line);
if (isdigit(line[0])){
rpn_stack.push_back(atof(line.c_str()));
}
}
rpn_stack is a vector since I will not be using the built in stack libraries in C++.
The problem I am currently having is that the output is just outputting "12". Why is this?
Is there a way that I can traverse through the file character by character instead of reading as a line? Is it breaking because it finds a white space (would that be considered the EOF)?
EDIT:
The code has been rewritten to be as the following:
string line;
while (!infile.eof()){
getline(infile, line);
for (int i = 0; i < line.size(); i++){
if (isdigit(line[i])){
rpn_stack.push_back(atof(line.c_str()));
}
}
}
The output is 12 5 different times, which is obviously wrong. Not only are there 4 items in the txt document, but only one of them is a 12. Can someone give some insight?
This will read as many doubles from infile as possible (i.e. until the end of file or until it comes across a token that isn't a double), separated by whitespace.
for (double d; infile >> d;)
rpn_stack.push_back(d);
If you need parse line-by-line, as #ooga says you will need a two-stage reader that looks something like this:
for (std::string line; getline(infile, line);) {
std::istringstream stream{line};
for (double d; stream >> d;)
rpn_stack.push_back(d);
}
Bonus hint: don't use .eof()

Reading a whole line from file in c++

I am working on a program in c++ and I need to read an entire string of text from a file. The file contains an address on one of the lines like this "123 Easy Ave" this has to be pulled into one string or char. Here is the code I have:
The data file:
Matt Harrold
307C Meshel Hall
1000 .01 4
The data is made up of a first and last name which become CustomerName, the next line is the address which is to populate Address, Then three numbers: principle, InterestRate, Years.
The code:
float InterestRate = 0;
int Years = 0;
char Junk [20];
int FutureValue;
float OnePlusInterestRate;
int YearNumber;
int count = 0;
char CustomerName;
string Address;
int * YearsPointer;
CustomerFile >> CustomerName
>> Address
>> Principle
>> InterestRate
>> Years;
Right now it only pulls in "103C" and stops at the space... Help is greatly appreciated!
Edit: In response to feedback on my question, I have edited it to use the more appropriate std::getline instead of std::istream::getline. Both of these would suffice, but std::getline is better suited for std::strings and you don't have to worry about specifying the string size.
Use std::getline() from <string>.
There is a good reference and example here: http://www.cplusplus.com/reference/string/getline/.
You'll also need to be careful combining the extraction (>>) operator and getline. The top answer to this question (cin>> not work with getline()) explains briefly why they shouldn't be used together. In short, a call to cin >> (or whatever input stream you are using) leaves a newline in the stream, which is then picked up by getline, giving you an empty string. If you really want to use them together, you have to call std::istream::ignore in between the two calls.
use std::getline from the <string> header.