So basically I want to find in my text file "NAPIS.txt" every line which has 2 letter "A" in it and then append number of these lines and lines themselves to new text file "wynika.txt". For some reason these lines append multiple times and there is too much of them.
here is code:
#include <iostream>
#include<vector>
#include<fstream>
using namespace std;
vector <string> t;
int main()
{
ifstream plikwe("NAPIS.txt");
ofstream pliwky_a("wynika.txt");
ofstream pliwky_b("wynikb.txt");
string temp;
int licz=0;
int licznik=0;
while(!plikwe.eof())
{
plikwe>>temp;
t.push_back(temp);
}
for(int i=0;i<t.size()-1;i++)
{
cout<<t[i]<<endl;
}
for(int i=0;i<t.size()-1;i++)
{
licz=0;
for(int j=0;j<t[i].size();j++)
{
if(t[i].at(j)=='A')
{
licz++;
}
if(licz==2)
{
licznik++;
pliwky_a<<t[i]<<endl;
}
}
}
pliwky_a<<licznik<<endl;
cout<<licznik<<endl;
return 0;
}
NAPIS text file
wynika text file
The below given complete working example shows what you want. It reads "NAPIS.txt" line by line and then checks if that line contains the character 'A' exactly 2 times or not. If the the line just read contains the character 'A' exactly 2 times then that line with corresponding line number is written to "wynika.txt" .
#include <iostream>
#include <fstream>
#include <algorithm>
int main()
{
std::ifstream inputFile("NAPIS.txt");
std::string line; //this will be used to read the line from the file
int currentLineNum = 0;//this will be used to write the current line number and write in output file
if(inputFile)
{
std::ofstream outputFile("wynika.txt");
while(std::getline(inputFile, line, '\n'))//read into line
{
++currentLineNum;
//check if line contains 2 'A' or not.
if(std::count(line.begin(), line.end(), 'A') == 2)
{
//std::cout<<"A found"<<std::endl;
//write the line number into wynika.txt
outputFile << currentLineNum << ' '; //you can skip this if you don't want to write the line number into the output file
//write the line into wynika.txt
outputFile << line << '\n';
}
}
//dont forget to close the file
outputFile.close();
}
else
{
std::cout<<"Input file cannot be opened"<<std::endl;
}
inputFile.close();
return 0;
}
The output of the above program can be seen here.
If you don't want to write the line number then you can comment(that is remove) the statement:
outputFile << currentLineNum << ' ';
from the above code.
Related
How do I remove/replace the last line of a file in C++? I looked at these questions:
Deleting specific line from file, Read and remove first (or last) line from txt file without copying
. I thought about iterating to the end of the file and then replacing the last line but I'm not sure how to do that.
Find the position of the last occurrence of '\n' in the file content. If the file ends with '\n', i.e there is no more data after the last '\n', then find the position of the previous occurrence of '\n'. Use resize_file to truncate files at the found position or just replace the content after the found position.
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
if (fin.eof()) {
fout << "text to replace last line";
} else {
fout << buffer << '\n';
}
}
fin.close();
fout.close();
}
Also you can read and store all your input file, modify and then write it:
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
// read
ifstream fin("input.txt");
vector<string> lines;
while (!fin.eof()) {
string buffer;
getline(fin, buffer);
lines.push_back(buffer + '\n');
}
fin.close();
// modify
lines[lines.size() - 1] = "text to replace last line";
// write
ofstream fout("output.txt");
for (string line: lines) { // c++11 syntax
fout << line;
}
fout.close();
}
I am trying to get the number of lines and words from a text file in c++. But one extra line is being read by compiler.
#include <iostream>
#include<fstream>
using namespace std;
int main(void)
{
ifstream f;
string name;
char a;
int line, words;
line = 0;
words = 0;
f.open("file.txt");
while (f) {
f.get(a);
if (a == '\n')
{
line++;
words++;
}
if (a == ' ')
{
words++;
}
}
f.close();
cout << "Number of words in file : " << words << endl;
cout << "Numbers of lines in the file : " << line << endl;
}
OUTPUT:-
Number of words in file : 79
Numbers of lines in the file : 3
file.txt:-
This C++ Program which counts the number of lines in a file. The program creates an input file stream, reads a line on every iteration of a while loop, increments the count variable and the count variable is printed on the screen.
Here is source code of the C++ program which counts the number of lines in a file. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
I am puzzled why one extra line is being read. Kindly help.
You are not checking if f.get() succeeds or fails. When it does fail, a is not updated, and you are not breaking the loop yet, so you end up acting on a's previous value again. And then the next loop iteration detects the failure and breaks the loop.
Change this:
while (f) {
f.get(a);
...
}
to this instead:
while (f.get(a)) {
...
}
That being said, you are also not taking into account that the last line in a file may not end with '\n', and if it does not then you are not counting that line. And also, you are assuming that every line always has at least 1 word in it, as you are incrementing words on every '\n' even for lines that have no words in them.
I would suggest using std::getline() to read and count lines, and std::istringstream to read and count the words in each line, eg:
#include <fstream>
#include <sstream>
#include <string>
#include <cctype>
using namespace std;
int main(void)
{
ifstream f;
string line, word;
int lines = 0, words = 0;
f.open("file.txt");
while (getline(f, line))
{
++lines;
std::istringstream iss(line);
while (iss >> word) {
++words;
}
}
f.close();
cout << "Number of words in file : " << words << endl;
cout << "Numbers of lines in the file : " << line << endl;
}
It is because you do not check in what state is stream that f.get(a) returns.
I've created a program that takes C++ code in one text file and outputs all of the comments from that code in another text file, however I've encountered a special situation, where the program does not do the necessary task. While it does extract most of the comments, it does not extract single line comments which are inside of a block comment.
Here is the C++ source code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream fin; //file that will be read
fstream fout; //file that will be written
string row; // string variable which will store each row of the code
string comment; // string which will store the comment
string blockCommentStart = "/*";
string lineCommentStart = "//"; // the beginning symbols of comments so that they could be identified in the text file
string result;
fin.open("code.txt", ios::in);
fout.open("endresult.txt", ios::out);
if(!fin) cout << "File not found" << endl;
if(!fout) cout << "File not found" << endl;
getline(fin, row); //reads the first row from the file
while(fin)
{
for(int i = 0;i<row.size();i++)
{
while (row[i]!= '/') //goes through the row until it finds the '/' symbol
{
if(i>row.size()) break;
i++;
}
if (i>row.size()) break; //checks if the end of the row has been reached
if(row[i+1] =='/' || row[i+1]=='*') //checks if the next symbol is the start of a comment
{
result = row[i];
result+= row[i+1];
}
if(result!="")
{
comment = ""; //creates a single line comment
if(result==lineCommentStart)
{
while (i<row.size())
{
comment+=row[i]; //the comment string adds the symbols of the comment
i++;
}
fout << comment << endl; //comment gets output in the endresult.txt file
comment=""; //after the output, it is renewed to the beginning stage
break;
}
comment = ""; //creates a block comment
if(result==blockCommentStart || result==lineCommentStart)
{
comment=row[i];
comment+=row[i+1]; //writes the comment symbols in the output file
i+=2; //jumps over the comment symbols
while(row[i]!='/') //adds symbols to the comment whilst it hasn't reached the end symbols
{
if(i>=row.size())
{
fout << comment << " "; //comment gets output in the endresult.txt file
getline(fin, row); //reads the next line
comment = ""; //comment string gets renewed for the new row
i=0; //moves the iterator back to the beginning position
}
comment+=row[i];
i++;
}
fout << comment << endl;
}
result = ""; //results gets renewed to the beginning stage
}
}
getline(fin,row); // reads the next line
};
fin.close();
fout.close(); //after the work is done, the files are closed
}
Here is the content of the test file code.txt:
// merge algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::merge, std::sort
#include <vector> // std::vector
using namespace std;
int main () {
vector<int> first = {1,5,8};
int second[] = {2,3,7,9};
vector<int> v(7);
merge (first.begin(),first.end(),second,second+4,v.begin());
std::cout << "The resulting vector contains:";
for(auto &i: v) cout<<i<<" "; cout<<endl;
}
/*
Comment which is in
multiple
// single line inside block
lines or a block
*/
//comment
Here is the result of the program(endresult.txt):
// merge algorithm example
// std::cout
// std::merge, std::sort
// std::vector
/* Comment which is in multiple /
//comment
So as one can see, the single line comment inside the block comment breaks the entire block comment structure. I would really appreciate any help or insight on how to solve this problem. Thank you!
EDIT: I've tried solving this further by replacing the
while(row[i]!='/')
line in the code near the blockComment segment with
while(row[i]!='/' || row[i-1]!='*')
and it now seems to include the single line comment however the formatting is a little wonky because the entire block comment then gets output together in a single line. Is there an easy solution to this, something like adding an endline after every row that is read?
I am creating a program that justifies a paragraph to ensure that each line has a length of 75 char. I have created functions that will insert spaces and create these desired lengths as needed, but I am having problems reading a text file and trying to break it down line by line. Each line provided is less than the 75 char limit, and my functions do properly work when it is given only a line. But I do not know how to read line by line, manipulate it, and then write to my new .txt file. When I output this to the new text file, I am greeted by a justified line of text, not text that is in a paragraph block!
I have tried to create an if else loop that would only run when the string.length() is less than 75 char, and would create a new line when false, but I do not know how to create this new line in the program
string myString;
string line("\n");
while (getline(inFile, myString))
{
cout << myString << endl;
puncLoop(myString);
spaceLoop(myString);
}
}
In Order to output the file with new line you can use "\n".
#include <iostream>
#include <string>
#include <fstream>
int main() {
//in file object
std::ifstream inFile("example.txt");
//out file object
std::ofstream outFile ("example2.txt", std::ios_base::out | std::ios_base::trunc );
//Checking if file exist
if( inFile && outFile )
{
//temp valarable to store each line
std::string mystring;
//Loop through each line
while (getline(inFile, mystring))
{
//... Call Your Business Logic functions here, ( make use of pass by refernce or return to get back the string )
outFile << mystring.c_str() << "\n";
}
//closing file after completing
inFile.close();
outFile.close();
}
else
{
std::cout << "Could not open File to read or write"<<std::endl;
}
return 0;
}
click here for the text file
I used the following code in Code::Blocks IDE. I get the number of lines as 2. Kindly help me with the code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream in("readInt.txt", ios::in);
if(!in)
{
cout << "Cannot open file";
return 1;
}
string str;
int j=0;
while(in)
{
getline(in,str);
j++;
}
cout << "No of lines are: " << j;
in.close();
return 0;
}
You get a too small result because the line endings in your text file are encoded in a different way than the convention on your system.
Save or recreate the file with correct line endings for your system.
In the other direction, towards a too high result, the presented code
while(in)
{
getline(in,str);
j++;
}
… would produce a count of 1 for an empty file.
Instead do
while( getline(in,str) )
{
j++;
}
Note: this remark only covers correctness, not efficiency.
First, your text file has not new character so in the text there is only one line
Change it and try in your code with
while(getline(in,str))
{
j++;
}
in this way you avoid to count extra line