#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file("file.txt");
file << "this is new line" << endl;
file.flush();
string c;
file >> c;
cout << c << endl;
file.close();
}
when i run this output is empty, if i remove line file << "this is new line" << endl; I'm getting correct output, why ?
By writing to the file, you are moving the internal file pointer to the end of it. This means the the next time you read, you will be at the end of the file, and so nothing will be read.
Look at seek() for moving the file pointer.
Related
I'm trying to learn about fstream and here is the code that I'm running on VS2019:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main() {
//cout << "lOOKING IN FILE";
string s;
fstream dictionary("C:/Users/source/repos/Test2/Test2/Text.txt");
if (!dictionary) // were there any errors on opening?
exit(-1);
while (dictionary >> s) cout << s << '\n'; // Print all names in file
dictionary.seekp(0, ios::beg); // Go back to beginning of file
cout << dictionary.tellp() << endl;
dictionary >> s;
cout << s; // Print the first name
return 0;
}
The output is:
abc
acb
cab
-1
cab
Why does tellp give -1 and not go to beginning of file?
You need to clear the state of the stream.
Once the state of a stream have changed from good (i.e. when it reaches end-of-file or there's a failure) then you can't operate on the stream again without clearing the state.
I want to load data from .txt file to variable and working with them (like calculate). When I open data, I can read them, but I donĀ“t know to work with data.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
fstream newfile;
string file;
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
while (getline(newfile, file)) {
cout << file << "\n"; //I GET OUTPUT CORRECTLY
}
newfile.close();
}
else
cout << "Error. \n";
cout << file << "\n"; //HERE IS PROBLEM. OUTPUT IS EMPTY
return 0;
}
I tried global variable, but it not solved. What should I do to correct it? Thanks
What you call "PROBLEM" in the comment is not a problem. file never contains more than a single from the file. The last call to getline will not read a line because there is nothing left in the file when you reach its end. So when you call
std::cout << file;
after that loop, it is to be expected that file is empty. If you want to use the lines later you should store them somewhere, eg in a std::vector<std::string>> :
int main()
{
fstream newfile;
std::vector<std::string> data; // vector to hold all lines
newfile.open("zadanie.txt", ios::in);
if (newfile.is_open()) {
string line; // better name (file->line)
while (getline(newfile, line)) {
cout << line << "\n";
data.push_back(line); // add the line to data
}
newfile.close();
}
else
cout << "Error. \n";
for (const auto& l : data) std::cout << l << '\n';
return 0;
}
Hello and thank you in advance. This is a very simple question but one that is getting on my nerves. What I want is just to ask for an integer to write to a file and then display every integer. I've learned how to either write to or display from a file and I've been successful at it but when I try to do both at a time it just asks me for the integer and don't display the numbers.
I think it may be a problem related to fstream or to the position of the pointer.
Here is the program:
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <fstream>
using std::cout;
using std::cin;
using std::fstream;
using std::endl;
int a;
int x;
int main() {
fstream in;
in.open("op.txt", std::ios::app);
cout << "Write an integer" << endl;
cin >> x;
in << " " << x;
while (in >> a) {
cout << a << endl;
cout << in.tellg();
}
in.close();
return 0;
}
There are a few things that are need to be fixed:
in.open("op.txt",std::ios::in | std::ios::out | std::ios::app);
here is why you need to do std::ios::in and out
the second problem is when you are switching between writing and reading from the file like you stated the problem is with the position of the read pointer
in.seekg(0, std::ios::beg);//before the while loop;
this sets the read position to 0 so the program can read from the file from the beginning.here
I want to open a random .txt file and put the data into some strings.
It works if I write the path into the code.
I don't get it why this doesn't work.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string file;
ifstream filein(file.c_str());
cout << "Insert Path" << endl;
cin >> file;
cout << file << endl;
filein.open(file.c_str(), ios::in);
for (string line; getline(filein, line);) {
cout << line << endl;
}
return 0;
}
Your filename string is empty because std::string defaults to empty.
You are passing an empty string (or the nul string) to the ifstream constructor, which is at best, undefined behavior.
Try writing your code like this:
#include <iostream>
#include <fstream>
int main()
{
std::string file;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, file);
std::cout << file << std::endl;
std::ifstream filein(file);
for (std::string line; std::getline(filein, line); )
{
std::cout << line << std::endl;
}
return 0;
}
Notable edits include:
We're now constructing the ifstream object only when we need it, after file has had data stored, which means no more undefined behavior, and that we only attempt to open a file after we know what the path is.
We're retrieving a whole line when storing to file, instead of only the first word, which is crucial if your path includes any spaces.
We're just using the file string directly. There's no need to call c_str().
We're no longer using using namespace std;. There are many, many reasons why this is bad practice.
EDIT:
If you have a C++17-compliant compiler, I'm going to propose you write code that looks like this instead:
#include <iostream>
#include <fstream>
//You may need to write #include <experimental/filesystem>
#include <filesystem>
#include <string>
int main()
{
std::string input_line;
std::cout << "Insert Path" << std::endl;
std::getline(std::cin, input_line);
//You may need to write std::experimental::filesystem
std::filesystem::path file_path{input_line};
//This will print the "absolute path", which is more valuable for debugging purposes
std::cout << std::filesystem::absolute(file_path) << std::endl;
std::ifstream filein(file_path);
for (std::string line; std::getline(filein, line); )
{
cout << line << endl;
}
return 0;
}
Explicit use of path objects will make your code more readable and make errors more explicit, as well as grant you access to behavior you otherwise would not be able to access.
first what are you opening? as long as you string doesn't contain anything??
second even if the string contains a valid path and the opening was successfull at the first time but in the second will fail as long as you use the same file stream on multiple files without clearing its buffer and closing the previous file:
string file "C:\\MyProject\\data.txt"; // let's say a valid path
ifstream filein(file.c_str());
if(filein.fail()) // the condition fails as long as the opening was successfull
cout << "failed to open file!" << endl;
cout << "Insert Path" << endl;
cin >> file; // let's say the user enters a valid path again: "C:\\MyProject\\test.txt"
cout << file << endl;
filein.open(file.c_str(), ios::in); // fail to correct it:
filein.close();
filein.clear(); // very important
filein.open(file.c_str(), ios::in); // now it's ok!
for (string line; getline(filein, line);) {
cout << line << endl;
}
I know i'm making a stupid mistake somewhere and even though i've been reading old questions i'm unable to catch it. I'm hoping someone would point me in the right direction. As you can probably tell i'm new to C++.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//local variables
string answer, filePath, wordtest;
fstream openFile;
***stuff removed for space reasons***
cout << "Enter the full file path" << endl;
getline(cin, filePath);
openFile.open(filePath, ios::in); //Open file
while (openFile.peek() != EOF)
{
cin >> wordtest;
cout << wordtest;
//getline(cin, wordtest);
{
//wordCount = wordCount + 1;
}
}
openFile.close();
openFile.clear(std::ios_base::goodbit);
cout << "Loaded file and read " << wordCount << " words";
}
You are neither reading nor writing to openFile.
You need to use operator<< or operator>> with openFile.