C++ - work with file (read file) then show in the console - c++

I would like to read the content from the text file by C++ , I wrote the code as below:
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
ifstream input("C:\\Users\\thang\\Desktop\\Thang\\output.txt");
string str;
while(!input.eof()) //check if it goes to the end of the file
{
//getline(input,str); //
input>>str; // get the value of str from the file
cout<<str<<endl;
}
return 0;
}
But it just show me the result with no empty row , but the output.txt file has the empty line.
I have attached the screenshot
Could you please help explain why it get the result without the empty line ? Appriciated for all assist.

Because the operator>> to read std::string from std::ifstream skips leading whitespaces. Newline characters is one kind of whitespace characters, so they are ignored.

Because input>>str strips away any leading whitespace.
If you just need to read the file like cat does, use rdbuf directly:
ifstream input(...);
std::cout<<input.rdbuf()<<std::endl;
If you want to iterate over the lines, including the empty ones, use std::getline
ifstream input(...);
for (std::string line; std::getline(input, line); )
{
...
}

Related

text turned into strange Chinese characters when trying to write to file C++

When I compile my code all is good no errors but when I open the file that I am writing too I see that most of the text has been converted into strange Chinese looking characters.
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string temp, line;
fstream file("LogData.csv");
fstream txtfile("temp.txt", ofstream::out, ofstream::trunc);
while (getline(file, line, '\n'))
{
txtfile << line;
}
file.close();
txtfile.close();
}

How to filestream strings(including spaces)?

I have an existing text file called database.txt. If I try to add a string at the end that contains a space, it only adds the string content until the space. How can I add the whole string input, including the spaces?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
fstream database;
database.open("Database.txt",ios::app);
cout<<"Name";
cin>>line;
database<<line;
database.close();
return 0;
}
Instead of using std::cin >> line; try use std::getline(std::cin,line);

Getline only printing out last line when called multiple times

So this is a fairly simple example of a program where I'm trying to output the first two lines of an input text file. The ifstream should be a global variable, and the testGetFile() function is necessary (I have not done the actual text processing needed in this code.) I'm trying to figure out why this is cout-ing only the SECOND line of the input file. Any help will be appreciated!
Thanks in advance!
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
ifstream input;
string testGetFile(){
string result;
getline(input,result);
return result;
}
int main(){
input.open("testInput.txt");
cout<< testGetFile();
cout<< testGetFile();
return 0;
}

Issue with reading file content

I have a file which contains text. I read line by line of the entire file and append to a string object. But when i get the final string print out i am not getting the whole file content. I am sure it is due to the presence of special characters like '\n', '\r', '\t', etc.
here is my sample code:
// Read lines until end of file (null) is reached
do
{
line = "";
inputStream->read_line(line);
cout<<"\n "<<line;//here i get the content of each line
fileContent.append(line);// here i am appending
}while(line.compare("") != 0);
This is the way to read a file into memory in C++:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
vector <string> lines;
ifstream ifs( "myfile.txt" );
string line;
while( getline( ifs, line ) ) {
lines.push_back( line );
}
// do something with lines
}
You’ll have to show more code for me to know what your problem is.
If you’re reading the entire file into a single string, this is the method I usually use:
#include <string>
#include <fstream>
#include <iterator>
std::string read_file(const char *file_name)
{
std::filebuf fb;
if(!fb.open(file_name, std::ios_base::in))
{
// error.
}
return std::string(
std::istreambuf_iterator<char>(&fb),
std::istreambuf_iterator<char>());
}

C++ Reading Files

What is the minimum code required to read a file and assign its contents to a string in c++?
I did read a lot of tutorials that worked but they were all different in a way so i am trying to see why, so if you could please include some explanatory comments that would be great.
Related: What is the best way to read an entire file into a std::string in C++?
#include <fstream>
#include <string>
int main()
{
std::ifstream file("myfile.txt"); // open the file
std::string line, whole_file;
// Read one line at a time from 'file' and store the result
// in the string called 'line'.
while (std::getline(file, line))
{
// Append each line together so the entire file will
// be in one string.
whole_file += line;
whole_file += '\n';
}
return 0;
// 'file' is closed automatically when the object goes out of scope.
}
A couple of things to note here. getline() returns a reference to the stream object, which fails the while-test if anything bad happens or if you reach the end of the file. Also, the trailing newline is not included in the string, so you have to append it manually.
The shortest code: (not effecient)
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
std::ifstream f("plop");
std::string buffer;
std::copy(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>(),
std::back_inserter(buffer));
}
How I would probably do it:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
// Find the size of the file
std::ifstream file("Plop");
file.seekg(0,std::ios_base::end);
std::streampos size = file.tellg();
// Read the file in one go.
file.seekg(0);
std::vector<char> buffer(size); // pre-szie the vector.
file.read(&buffer[0],size);
// or
// Until the next version of the standard I don't think string gurantees contigious storage.
// But all the current versions I know do use continious storage so it should workd.
file.seekg(0);
std::string buffer1(size);
file.read(&buffer1[0],size);
}
I'm not seeing as much:
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ifstream ifs("filename");
stringstream ss;
ss << ifs.rdbuf();
string s = ss.str();
}
... as I'd expect. You'd want some error-checking too.
Konrad Rudolph gave this as the answer to the "related question" linked above. I suppose this isn't a duplicate, since this asks for the shortest code, but the answer is the same either way. So I repost it here as wiki.
I am reading a word from each line.
#include<fstream>
#include<string>
using namespace std;
int main(int argc, char **argv)
{
fstream inFile;
string str;
while(!inFile.eof())
{
inFile.open("file.txt");
infile>>str;
}
inFile.close();
return 0;
}
This is longer than the short solutions, but is possibly slightly more efficient as it does a bit less copying - I haven't done any timing comparisons though:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;;
unsigned int FileRead( istream & is, vector <char> & buff ) {
is.read( &buff[0], buff.size() );
return is.gcount();
}
int main() {
ifstream ifs( "afile.dat", ios::binary );
const unsigned int BUFSIZE = 64 * 1024;
std::vector <char> buffer( BUFSIZE );
unsigned int n;
string s;
while( n = FileRead( ifs, buffer ) ) {
s.append( &buffer[0], n );
}
cout << s;
}
If you know that your file contains text, then you can use STLSoft's platformstl::memory_mapped_file:
platformstl::memory_mapped_file file("your-file-name");
std::string contents(static_cast<char const*>(file.memory()), file.size());
or
platformstl::memory_mapped_file file("your-file-name");
std::wstring contents(static_cast<wchar_t const*>(file.memory()),
file.size() / sizeof(wchar_t));
On WIndows, that will leave your string containing \r\n sequences, so you could instead use the winstl::load_text_file() function:
std::string contents;
winstl::load_text_file("your-file-name", contents);
If you want it loaded into a collection of lines, then use platformstl::read_lines():
platformstl::basic_file_lines<char> lines("your-file-name");
size_t n = lines.size();
std::string line3 = lines[3];