I have searched through a lot of questions on this website which are pretty much the same, but nothing works for me. In the first place, let me tell you that I am using Code::Blocks and I am using Ubuntu. This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("code.out");
string write;
getline(cin, write);
file << write << "\n";
file.close();
}
Tried \n, tried \r\n (\r doesn't seem to do anything for me really). Oh and by the way, if you could also make it work with word-by-word reading that would be great. Thank you very much!
EDIT: Hey guys, I solved it. Thanks for the answers tho! I needed to add a ios::app after code.out!
Should you be using ofstream. http://www.cplusplus.com/reference/fstream/ofstream/
Then check that it has opened.
Then check you have read some data - debugger is handy for that
EDIT
You need
ofstream file("code.out", ios::out | ios::app)
Try this code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
fstream file("code.out", std::fstream::out);
string write;
getline(cin, write);
file << write << '\n';
file.close();
}
Explicitly passing the std::fstream::out through the constructor got it to behave correctly for me and produced the newline.
Edit:
Note for future reference, my solution produces the newline but this will overwrite data currently found in the file. Ed Heal has code for appending to a file in his answer.
Adding
std::fstream::app
to my code would then mimic Ed Helms solution. Please mark his answer if appending functionality is actually what you needed. This answer will be for others who have a similar newline issue who want to overwrite the file.
I also had that problem once.
Try using ofstream instead of fstream. Maby that'll help, because I used that too.
Related
I'm a beginner and I'm trying to transform from previous version of c++ to modern c++17.
I'm trying to read lines from a file. The contents are mostly gibberish and I'm doing this as an exercise to learn the language after not using c++ for many years.
The contents of the file I'm reading from are gibberish, i.e:
werweirwer
weriwrwjeie
werjiwrji
(after solving this I'll use it as an exercise to assign lines after filtering as input to constructors, use regex on it and basically develop it until I feel comfortable enough with input/out concepts, which may take some time).
However, it cannot read from the input file, even though it exists and in the same directory as the .cpp file (with reading permissions). IDE is clion if it matters.
Here's the code I used:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
std::vector<std::string> insertToVector(std::string k){
std::vector<std::string> wordvector;
if(k.empty()) {cerr<<"error reading from file: string is empty";}
else {wordvector.push_back(k);}
return wordvector;
}
int main() {
fstream f("k.txt",ios_base::in);
std::string templine;
if(f){
cout<<"Contents: \n";
while(getline(f, templine)){
cout<<"Contents:"<< templine; //just to output it simply
std::vector<std::string> wordvector= insertToVector(templine);
std::for_each(wordvector.begin(),wordvector.end(),[](const std::string word){std::cout<<word;}); //vector output
}
}else{
std::cerr<<"couldn't open file";
}
f.close();
return 0;
}
Additional question I wonder whether it is good to read lines with while(getline()) or to use while(!f.eof()) instead? Which is better in your opinion?
One more thing, I'm quite confused with functors and std::function, could you show me how to implement the insertToVector as std::function or functor and call it correctly?
Thank you very much. Doing my best to learn
EDIT: Fixed it using auto path = fs::path, and then using that reference with fstream. Worked well. Thank you very much for your explanations in the comments. Helped a lot in learning.
I am currently learning C++ and I was trying to add text to a file, but it keeps overwriting it, is there anyway I can append stuff to it?
#include <iostream>
#include <cstdlib>
#include <fstream>
int main()
{
std::ofstream fil3;
fil3.open("test.txt");
file3 << " bye!"; // replaces text already existing in file :(
fil3.close();
return 0;
}
So, I already have a text file with the words "Good" in it and I wanna try adding "bye!" to it so I have "Good Bye!". Can someone explain to me what function I should be using here? Thanks!
When you open the file, use the append flag:
file3.open("test.txt", std::ofstream::app);
You can read more about file operation options here.
I have the task to write a function that reads a line from a text file (renamed to .dat, however it contains only text), but I am out of options for a solution because of the following points:
I am using Borland C++ Version 5.02, and no, I CAN´T download another compiler because I dont have admin rights on my laptop and the guy who has the needed password isnt there until next week.
The compiler does not accept using namespace std, and also it doesnt accept getline(), no matter if string and iostream are included or not.
I am trying to find a solution or at least the tiniest approach, but I am unable to find one.
So my question is: How do I read a line from a simple textfile without using getline() (cin.getline works, the ones from string or fstream doesnt) ? The textfile contains several lines like these:
1234;12.05.03;08:44:23; XY12-AB;A1-12;Timeout
2345;12.05.03;09:04:34;XY1-CD;A22-9;Connection refused
And the numbers/letters between the ; need to be stored in variables so they can be worked with.
Im not asking for you to write my code, but I am reallyreaylly frustrated and my instructor is no help.
Live long and prosper,
Me.
http://www.cplusplus.com/reference/string/string/getline/
If you cant use (which you really shouldnt)
using namespace std
Then refer to your namespace with :: operator
For example:
std::string
Now try to write your own code using std:: and comment if you still cant do it.
Also, there is a lot of other options than std::getline() to read line of text.
Ref: Read file line by line
Option 1:
Try using the C's fgets() function.
Option 2:
You mention that cin.getline() works. You can freopen stdin with the input file and then cin will point to mentioned file. After that cin.getline() will read from the file:
Downside: After the freopen you will not be able to accept any input from the user.
Example: Note this has not been tried using g++ but I guess it should work with Borland too.
#include <iostream>
#include <stdio.h>
int main() {
char buf[1000];
freopen("somefile.dat", "r", stdin);
while (cin.getline(buf, sizeof(buf)).good()) {
// Now buf contains a line
// Do something with it
}
return 0;
}
Try using
getline(cin >> ws, variableName);
But first, you have to use
using namespace std;
I'm having the same problem while i using multi dimensional array on structs into a file, i have try different ways. But then i tried this one and it's work for me.
So in my case it gonna be like this
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream myFile;
myFile.open("test.txt");
int count = 0;
while (!myFile.eof())
{
getline(myFile >> ws, data[count].string1);
getline(myFile >> ws, data[count].string2);
myFile >> data[count].int1;
for (int i = 0; i < data[count].int1; i++) {
getline(myFile >> ws, data[count].data2[i].string3);
}
count++;
}
return 0;
}
For more : https://www.geeksforgeeks.org/problem-with-getline-after-cin/
Ok so I haven't used C++ since highschool (used to work in borland C++)
Now I want to solve a problem in C++, yet I don't understand why fstream doesn't work
For some reason ios::in doesn't work.
#include <fstream>
fstream f("Cities.txt,ios::in);
How do I use Fstream properly?
Thanks in advance!
Note : I'm using Visual Studio 2008
change from
fstream f("Cities.txt,ios::in);
to
std::fstream f("Cities.txt" , std::ios::in);
^^^ ^ ^^^
namespace you miss" namespace
done!
What you have learned in your highschool probably was way before C++ was standardized in '97. As per the standard, all C++ library functions are part of the std namespace. In order to use fstream which is part of the standard namespace, you have to qualify it with std:: so, that makes your syntax as
#include <fstream>
std::fstream f("Cities.txt",std::ios::in);
As an alternative to std::fstream, consider std::ifstream (and std::ofstream):
#include <fstream>
…
std::ifstream f("Cities.txt");
std::ofstream o("output.txt");
std::string s;
while( f >> s )
o << s;
Personally, I find this more convenient than specifying the open mode.
You have to first create an object of ifstream class and then open the file.
Do it this way.
#include <fstream>
std :: ifstream f ("Cities.txt",ios::in) ;
Then check whether it is open and start working with it.
You are also missing the " after file name.
You can also write
#include <fstream>
using namespace std;
fstream f("Cities.txt",ios::in);
The using directive allows you to not write std:: before everything. Beware, it might be bad practice, but in small programs it should not be an issue.
I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?¨
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}