Reading Line by Line in C++ for Pairs [duplicate] - c++

This question already has answers here:
reading text with whitespaces in c++
(2 answers)
How to read the whole lines from a file (with spaces)?
(4 answers)
Closed 4 months ago.
I have an input file that looks something like this:
0.1 239.402
0.4. 32342.34
0.7 4.924939
and so on...
I am trying to read it line by line using the fstream extraction operator >>
I need a way to set a while loop condition that would stop at the end of the file, and I need a way to push the two as a pair onto two stacks
The stacks are previously implemented in a class file Stack as linked lists
I currently have something like
double a, double b
std::string t;
Stack av;
Stack bv;
while(i>>a>>t>>b&&(t=="\t"){
av.push(a);
bv.push(b);
}
i know i'm incorrect as it's not always a tab space gap. also the file starts with a couple of spaces until the first row and then has a random number of spaces until the second row, and then a next line.
Is there a way to write a program where it knows when there is a double to read and use the random number of whitespaces as separation between a and b?
I hope this makes sense! Thanks so much for your help as I'm a beginner.

Related

simple fortran program to print back what it reads [duplicate]

This question already has answers here:
Using a deferred-length character string to read user input
(4 answers)
Reading a string with spaces in Fortran
(2 answers)
Reading a character string of unknown length
(4 answers)
How to read text files with possibly very long lines in Fortran
(2 answers)
Closed last month.
It's a very simple task, but there are two problems with my current implementation.
I want it to read a whole line. It currently only reads the first few characters if they are separated by space. I think this can be fixed with a custom format, but I don't know what to use.
Fortran needs to know how much to allocate and with my current implementation it can only read 10 characters. I want it to read without a limit. The only way that I know that can fix this right now is asking the user, how many characters they want to be read, but other programming languages can do this without it and I don't want to ask the user for additional things.
program main
implicit none
character(:), allocatable :: name
allocate(character(10) :: name)
read *, name
print *, name
deallocate(name)
end program main

Returning to a specific place in a file after extraction of characters [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a question, after I loop on a file and extract several letters with a counter to know how many characters have been extracted how can I reposition my pointer to point back the first one extracted. Here is what I have tried so far:
int get_length(ifstream &inp,int &length){
int columns=0;
inp>>columns;
length++;
while(columns!=0)
{
inp>>columns;
length++;
}
if (!inp.good())
inp.clear();
inp.seekg(-length,std::ios::cur);
return length;
}
For some reason its not going back the same length, it's getting it wrong by one, I've tried adding to length by one then writing that seek function I don't know what's wrong here, I'm questing if I'm using the seek function incorrectly?
I think that the problem is this:
You are incrementing 'length' each time an integer value is read from the fstream 'inp'. Depending on on how many characters wide the integer representation is you will need to increment length by that amount. That and new-line chars and any other whitespace in the fstream.
If your test data contains:
10
11
12
13
Then by the time you read 13 you will have consumed 12 bytes of file data.
Your counter will have only incremented 4 times.
You could do this more easily and accurately by placing a call to
auto const position_start = inp.tellg();
at the start of your function and once you read the data you're interested in 'rewind' to the start position with a call to
inp.seekg(position_start, std::ios::beg);
'ifstream' is a specialisation of 'basic_ifstream', so 'ifstream::seekg()' takes an offset in bytes (chars). However, the formatted input (to an int) will advance the the current position by some number of bytes (0 or more) as it converts the input to an integer value. Use 'ifstream::tellg()' at the top of the function to get the current file position and another call to 'tellg()' before calling 'seekg()' to get the new file position. The difference in the two values will be 'length'.

Reading in one byte at a time with .get() [duplicate]

This question already has answers here:
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 7 years ago.
So i'm reading in a input file that contains:
lololololololol
I need to read it in using binary one byte at a time for something I'm doing later on. To do this i'm using get() to read it in then storing it into a char. It seems to be working correctly except for the last char that it reads in. The vector that it is reading into contains:
lololololololol
�
I'm not quite sure what this last value is but it's totally throwing off my finial output. So my question is, is there a reason get() would read in a value or byte from my text document that is not there? Or is it reading in something that I don't know of?
code:
while(istr.good()) {
temp = istr.get();
input.push_back(temp);
}
It's reading the EOF (end of file) character. You need to do the check after reading it to avoid it being inserted to the vector:
while(temp = istr.get(), istr.good()) // comma operator
input.push_back(temp);
Or you might use the 2nd std::istream_base::get overload and let istr implicitly convert to bool:
while(istr.get(temp))
input.push_back(temp);
Or try more advanced approaches. operator>> and std::getline would also work fine for this kind of input.

C/C++ code for rearranging .txt file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi i have to make a function in C++ that gets one file as an input and as an output it has another file, that is rearranged in a specific way. In the file there are names of people,names of subject they are teaching, commented lines starting with '#' and also duplicated white spaces. The input file looks like this (before ':' are the names, after it are the subjects):
john : PA1 , PA2,OSY
#this is commented line
peter: PA1, PA2
And the output in the second file should look like this:
OSY: john
PA1: john, peter
PA2: john, peter
As you can see, the function should put one subject on each line (in alphabetical order) and then there should be ':' and after that the names of the people teaching it (also in aplhabetical order). Also all commented lines should be deleted and the same with duplicated white spaces.
I know how to delete duplicated white spaces and commented lines, but I have problem with rearranding the people and subjects. Is there any possible way to do this function without using classes?
I would be very thankful for any help or advices.
bool transform ( const char * inFile,
const char * outFile )
{
// todo
}
There are various different problems to solve. You must first identify those individual problems, then solve them one by one, and then put the pieces together. Many years ago, when I was a student at university, this approach was taught to me as "divide & conquer".
Here are the individual problems I can identify in your question:
Read a text file's contents into memory, so that you deal with strings and each line is a string.
Parse a string. Split it into substrings, so that you deal with a collection of strings (tokens). Know when a string starts with a particular character.
Create a data structure in which a sorted, unique string key relates to a list of (likewise ordered and unique) strings.
Write a series of strings to a text file.
Each of the sub-problems may well be individual separate questions on Stack Overflow. I'll give you hints for every one of them, so that you can google them or browse the archive for related questions:
Reading a text file line by line in order to end up with a series of std::string objects is best done with std::ifstream and std::getline.
Getting the first character of a std::string is easy: my_string[0], first checking if !my_string.empty(). Splitting it is more difficult. I would personally use the occasion and get started with the Boost libraries. See the Boost Tokenizer example.
The data structure you need is already there - C++ itself provides it as part of the language. The first thing which comes to mind is std::map<std::string, std::set<std::string> >.
Writing is simpler: use std::ofstream and write line by line with operator<<.
std::map and std::set are your best friends here.

C++ Fastest way to parse through a file

I have a file which I have opened using:
ifstream ifile(FilePath)
The file contains, say 10 lines of data and each line contains an evenly-incrementing number of comma separated values (like a pyramid). So first line has 1 value, second line has 2 values and so on....
I wanted to do the following, all within one function (whilst traversing the file char array just the once):
-Every time I encounter a newline character, I can increment a parameter passed in by value (which, when the function exits, I have the number of lines in the file).
-I also wanted to store each line of the file in an array. What would be the best way to "glue" together all the characters between newline characters?
I'd prefer to use statically-allocated arrays, but the problem is I only know the size of the array once I have performed step 1 (counting how many new line characters there are). Would it be quicker to perform a double-parse for this (one parse to count how many lines, then use that value to allocate a static array) or single parse, but insert into a dynamic array?
The emphasis on this is to write fast code (so not being OO-friendly is not a concern)
Apologies if I am asking a lot, hopefully you can see I have given this some thought.
EDIT, example file:
a
b,c
d,e,f,g,h
j,k,l,m,n,o,p
From this file I would want to achieve:
Knowledge that there are 4 lines in the file
A non-dynamic array containing each line
The number of elements in the second line
There are plenty of examples in existing posts on how to do this.
if you want to use ifstream to read in the file once, you can do something like this:
std::ifstream in("myfile");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());