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
Related
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.
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?
first i want to apologize for my english. I want to create a program that reads each line from a .txt file and adds for each line #" in front and " at the end. Example: #" i like apples". This is my code so far that replaces ".", "?" and ":" but i don't want that.
#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <values.h>
int main()
{ ifstream f;
f.open("lala.txt");
if(!f)
{
cout<<"Eroare la deschiderea fisierului!"<<endl;
}
char s[100],x;
int i,n=0, k=0;
ofstream g("adinarez.txt");
f.seekg(0,ios::beg); //ne pozitionam la inceputul fisierului
while(f)
{
f.get(x);
s[k]=x;
n++; k++;
}
f.close();
for (i=2; i<n-1; i++)
if((s[i]>=65) && (s[i]<=90))
{ s[i-1]='\"';
s[i-2]='#';}
for(i=0;i<n;i++)
if(s[i]=='.' || s[i]=='?' || s[i]==':' || s[i]=='\0')
s[i+1]='\"';
for(i=0;i<n;i++)
g<<s[i];
g.close();
return 0;
}
For starters, if you're processing line oriented input, use
std::getline to read line by line; don't use std::istream::get.
Also, you need to check the status of the stream after the read, not
before. Something like while ( std::getline( f, line ). And line
should be an std::string, so you don't have to worry about overflow.
(Sort of. If a line contains more memory than the program can allocate,
you'll crash with an uncaught std::bad_alloc. But that will be a lot
more than a hundred characters.) Once you've got the line, you can use
the << operator on the output stream to output it. Along with
anything else you want to output.
If I correctly you understand offer this way:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string line;
std::ifstream myfile("1.txt");
std::ofstream outfile("2.txt");
if(myfile.is_open())
{
while (getline(myfile,line))
outfile<<"#"<<line<<std::endl;
myfile.close();
}
else
std::cout << "Woops, couldn't open file!" << std::endl;
return 0;
}
I'm kind of a newbie in C++ programming.. My command prompt output is a big bulk (repeated) of the characters I have in my txt file. I create a 2d array map[15][15] and try to read the txt file. the reading part is ok but now I dunno how to put them in a 2D character array..
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
char map[15][15];
int alp = 0;
int i = 0;
int main()
{
ifstream in;
//string s;
in.open("city.txt");
if(!in.is_open())
{
cout << "File open error! " << endl;
}
else
{
while(!in.eof())
{
//getline(in, s);
in >> map[i];
i++;
alp++;
//if(in.eof()) break;
cout << map[i] << endl;
}
}
for(i = 0; i <= alp; i++)
{
cout << map[i];
}
in.close();
return 0;
}
eof() will only return true only after the first failed read operation. That operation will not be caught by your code. You could have a test for eof directly after the read and then break if eof(), but that's not elegant:
IO operations on streams return a ref to the given stream. Streams have a meaningful conversion to bool. True indicates that the read was successful, e.g. eof wasn't reached yet, and the read target contains a new correct input value. The idiomatic way of using this feature is "while(in >> map[i])".
As to the algorithm: You say that there are no spaces and I assume it's all ascii chars, so it boils down to double looping over the array's lines and columns with two for loops. Inside those loops would be a line reading each character explicitly with get() like
if(!cin.get(map[i][j])) {/* unexpected eof/io error, abort or whatever */ }
As the data is textual, and separated into lines, I suggest you read directly into the sub-array using e.g. std:istream::getline:
for (size_t i = 0; in.getline(map[i], 15); ++i)
;
I'm in a tutorial which introduces files (how to read from file and write to file)
First of all, this is not a homework, this is just general help I'm seeking.
I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.
What if my file contains 1000 words? It is not practical to read entire file word after word.
My text file named "Read" contains the following:
I love to play games
I love reading
I have 2 books
This is what I have accomplished so far:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ifstream inFile;
inFile.open("Read.txt");
inFile >>
Is there any possible way to read the whole file at once, instead of reading each line or each word separately?
You can use std::getline :
#include <fstream>
#include <string>
int main()
{
std::ifstream file("Read.txt");
std::string str;
while (std::getline(file, str))
{
// Process str
}
}
Also note that it's better you just construct the file stream with the file names in it's constructor rather than explicitly opening (same goes for closing, just let the destructor do the work).
Further documentation about std::string::getline() can be read at CPP Reference.
Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.
std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("filename.txt");
string content;
while(file >> content) {
cout << content << ' ';
}
return 0;
}
I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
The above solutions are great, but there is a better solution to "read a file at once":
fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
hello bro this is a way to read the string in the exact line using this code
hope this could help you !
#include <iostream>
#include <fstream>
using namespace std;
int main (){
string text[1];
int lineno ;
ifstream file("text.txt");
cout << "tell me which line of the file you want : " ;
cin >> lineno ;
for (int i = 0; i < lineno ; i++)
{
getline(file , text[0]);
}
cout << "\nthis is the text in which line you want befor :: " << text[0] << endl ;
system("pause");
return 0;
}
Good luck !
Another method that has not been mentioned yet is std::vector.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
The below snippet will help you to read files which consists of unicode characters
CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
if (0 == errCode)
{
CStdioFile File(fStream);
CString Line;
while (File.ReadString(Line))
{
plainText += Line;
}
}
fflush(fStream);
fclose(fStream);
you should always close the file pointer after you read, otherwise it will leads to error