Skip last K lines while traversing a file [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A user had posted a similar question earlier this day which was very soon closed due to its vagueness. Thus re-posting the question in detail with a solution as I didn't find a specific article dealing with it on the internet.
The requirement is to read and print all lines of a file except the last K.
Suppose a file contains text as:
Hello there!
My name is
Mr. XYZ
I like playing football
And if K is 2, then it should print all the lines except the last 2. i.e.:
Hello there!
My name is

Why not simply put lines into a std::deque and dump one element when its size is greater k ?
#include<iostream>
#include<fstream>
#include<deque>
int main()
{
std::fstream fs;
fs.open("output.txt",std::ios::in);
std::deque<std::string> deq;
std::string str;
int k=2;
while(std::getline(fs,str))
{
deq.push_back(str);
if(deq.size() > k)
{
std::cout <<deq.front()<<std::endl;
deq.pop_front();
}
}
}

This can easily be solved by creating a window of size K and then traversing the file till the right end of the window reaches the end of the file. The basic steps being:
Traverse the first K lines of the file without printing it.
Open the same file using another stream object.
Now simultaneously traverse both the streams so that fisrt stream is always K lines ahead of the second stream.
Run a loop while the second first stream is valid. In the loop, read through the first stream as well and keep print the lines.
The code would be
#include<iostream>
#include<fstream>
#include<string>
int main()
{
fstream fs;
fs.open("abc.txt",ios::in);
string str;
int K = 2;
while(getline(fs,str) && K>1)
{
K--;
}
if(K==1)
{
fstream fsNew;
fsNew.open("abc.txt",ios::in);
while(getline(fs,str))
{
getline(fsNew,str);
cout<<str;
}
}
cin.ignore();
}

Related

Reading from 3 column txt file to different arrays [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 5 years ago.
Improve this question
I want to read a three column and N row txt file to three different arrays:
int N=100;
double x[N],
y[N],
z[N];
ifstream reading;
reading.open("reading.txt");
reading.close();
What should I write in the empty region? x[j], y[j], z[j] should be element in j'th row and first, second and third column respectively.
Once you get the input file stream, it will be similar to reading from a standard input.
As a hint I can say, what about reading every integer and then store them appropriately. For example,
1 2 3
4 5 6
7 8 9
Now you read everything like this
while (redaing>> num) {
// here you would know whether you are reading the first number
// or second number or third.
// x[xi] = num or y[yi]=num or z[zi]=num
}
Also you need to do something before you start reading from a file using the input file stream.
Have this check to make the program more safe.
if (!reading) {
cerr << "Unable to open file reading.txt";
exit(1); // call system to stop
}
A solution would be like this:
int xi=0,yi=0,zi=0,iter=0;
while(redaing >>num){
if(iter%3==0)x[xi++]=num;
else if(iter%3 ==1)y[yi++]=num;
else
z[zi++]=num;
iter++;
}
More succintly as pointed by user4581301
while(redaing >>x[xi++]>>y[yi++]>>z[zi++]){
//..do some work if you need to.
}
Also another from comment to limit the 100 line reading is [From comment of user4581301]
int index = 0;
while(index < 100 && redaing >>x[index]>>y[index]>>z[index] ){
index++;
}
A better solution:
vector<int> x,y,z;
int a,b,c;
while(reading>>a>>b>>c){
x.push_back(a);
y.push_back(b);
z.push_back(c);
//..do some work if you need to.
}
I'm kind of confused on the wording of your question could you try and reword It? Also if you want to read to the nth row I would use a while loop with the condition being while not end of file. Also you may consider using a vector since you don't know how large of an array you want to create.
A trivial way is
Read the file line by line using getline().
Get the line into an istringstream.
Use istringstream as any istream like cin, it will only contain one line of text.
I would suggest you to search for these terms on some website like www.cppreference.com if you don't know them.

what is the time complexity of this program? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I'm new to time complexity in algorithms.
This is the code for counting the number of words in a text file.
My problem is that every time my program prints one more than the actual count of words in the file, like if I have 11 words in my file it prints 12.
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
/* main function */
void main()
{
ifstream inFile; //file file name
string fileName;
string word;
int count = 0;
inFile.open("example.txt");
while(!inFile.eof())
{
inFile >> word;
++count;
}
cout << "Number of words in file is " << count<<endl;
inFile.close();
}
//this file is for counting the number of words in a text file**
First thing first : Why is iostream::eof inside a loop condition considered wrong? This will answer your extra count problem.
Then, coming to complexity, since it will go though every N words till it reaches end of file, it will be done in O( N ) time
Also, void main() is not legal c++, main should return int

Issue in file operations in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is part of a c++ code that writes value of a vector of strings into a file.
int main () {
//freopen ("out.txt", "w+", stdout);
ofstream data;
data.open("data.txt");
BinaryTree<string>* bt = new BinaryTree<string>;
LoadBinaryTree(bt);
fillArrayOfNodes(bt);
for (int i = 0; drawArray[i] != "\0"; i++)
data << drawArray[i] << endl;
data.close();
delete bt;
return 0;
}
First, I couldn't write into the file. I mean after running the program and checking the output file, it was empty. after that, I noticed that my output format wasn't right. I changed it and now I can write into the file. (the code shown above is the modified code)
The problem is the way you're attempting to iterate through the array. The Standard C++ string class std::string should not be handled like a regular char array. That is, you shouldn't base your condition upon finding the null character. The correct way would be to iterate until you reach the length of the string.
Moreover, you should be using a vector of strings and inserting strings using push_back():
std::vector<std::string> v;
// fill vector with push_back()
for (int i = 0; i < v.size(); ++i)
data << v[i] << endl;
You need to include the right headers like <fstream>.
Try this example: http://www.cplusplus.com/doc/tutorial/files/

Simple text editing program in C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I got a little bit of trouble creating a program that edits text in C++. Keep in mind that I'm still at the beginning of programing. Here is what I must do:
Some text is placed in text file F. I must write a program-editor, which based on the file F, commands and data from the keyboard creates the file FF. The program-editor must recognize and process the following commands:
AN - insert text after the n-th row;
IN - insert text before the n-th row;
CM,N - substitution of the rows from m-th to n-th;
DM,N - deleting the rows from m-th to n-th;
E - end of editing;
where m and n are the number of rows in the file F.The commands are recorded one on row and are made as a menu.
This is the program. I researched a lot in the web about text editing and there are some text editing programs' source codes, but I guess I'm still in the beginning of programing and I find those source codes really difficult to understand. I'm concerned about few things:
Must I manually put text in the text file F and must I add another option in the menu about adding text;
The other thing is about the commands - how do I find and use the different rows from the text so I can insert, substitute and delete rows;
Well that is all. If you have the time please help me, because I really need to know how this program must be done in a not so complicated way and I think it got some valuable things that I could learn from it. Thanks in advance !
In pseudo-code, you ll find every real function you ll need in the documpentation.:
You ll need to write parse() yourself, all vec.something and input.something are real vector or string function, under a different name, you ll need to search the documentation.
open, close and writeinfile are io function under different name too (and different parameters), again, see the doc
getuserinput is also a renamed basic io function.
The reason I write this is to give you an idea of how to do this, it is not the solution spoon feeded to you, think of it as the algorithm, if you can do your homework without it, it is far better than using it. Also, learn to search the doc, it is really useful
vector<string> vec
int n, m
string input, output
//Open the file
open(your_file)
//Store every line in a string in the vector
while(input != EOF)
{
input = getalinefrom(file)
vec.add(input)
}
//You don t need the file for now, so close it
close(file)
//Create your 'menu', presuming text based, if graphical, well...
do
{
//Get user choice
input = getuserinput()
//Every command is just a letter, so check it to know what to do
if(input.firstchar == 'A')
{
//Parse the input to get n
n = parse(input)
//Get the line to add
input = getuserinput()
//Add it before n
vec.addafter(n, input)
}
else if (input.firstchar == 'I')
{
//Parse the input to get n
n = parse(input)
//Get the line to add
input = getuserinput()
//Add it before n
vec.addbefore(n, input)
}
else if (input.firstchar == 'C')
{
//Well, I don t see what is substitution so I ll let you try
}
else if (input.firstchar == 'D')
{
//Get n and m
n = parse(input)
m = parse(input)
//Presuming n < m, you ll need to check for error
while(n < m)
{
vec.deleterow(n)
n = n + 1
}
}
//Go out of the loop at E since it s the end of the app
}while(input != "E");
//Concatene every line
n = 0
do
{
output = output + vec.contentofrow(n)
}while(n < vec.length)
//Open the file again, with correct flag it will erase it content
open(file)
//Write your new content
writeinfile(file, output)
//Close the file
close(file)
return 0;

how to read data in c++ from a file stored in any other structure e-g: .text file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
i gotta read data in c++ from a text file stored in computer
and then tokenize the data on the basis of space so that each word becomes a separate string
i have tried a code but it doesn't print anything as an output instead of a black blank screen
// basic file operations
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
//using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");``
myfile << "Writing this to a file.\n";
// myfile.close();`
getch();
return 0;
}
please help :(
The code you have posted does not attempt to write anything to standard output (std::cout). It opens a file (example.txt) and writes "Writing this to a file" in it, closes the file, and then waits for you to press a button before exiting the program. You are seeing no output because you've provided no output operations, nor does it attempt to read anything from the file.
First use ifstream since you want this file as input not output
Second what is this code you posted has to do with the question?
Try this:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file("example.txt");
if (file.is_open())
{
std::string str;
while (std::getline(file, token, ' '))
{
//here str is your tokenized string
}
} else
{
std::cout << "Unable to open file";
}
}
getline will get the next string until the end of line or ' ' is met
This code WRITES to a file...maybe there's a C++ way to do it but strtok does what you describe.
Found within a minute of googling :)
using namespace std;
string STRING;
ifstream myReadFile;
myReadFile.open("Test.txt");
char output[100];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
getline(myReadFile,STRING);
cout << STRING;
}
myReadFile.close();
}
Edit: Fixed the thing and tested it with success.