No matching function for call when reading file - c++

I'm getting an error when I'm trying to open my file and perform a read operation on my second file. I'm not sure what went wrong.
error: no matching function for call to ‘std::basic_fstream<char>::open(std::string&)’
file.open(filename);
int main()
{
DoublyLinkedBag<string> dictionary;
fstream file;
string word;
file.open("dictionary.txt", ios::in); // open a file to perform read operation using file object
if (file.is_open()) // check whether file is open
{
while (file >> word)
{
dictionary.add(word);
}
}
string filename;
string words;
cout << "Enter the name of the file that contains words to check:" << endl;
cin >> filename;
file.open(filename);
if (file.is_open())
{
while (file >> words)
{
if (!dictionary.contains(words))
{
cout << "The following words in the file " << filename << " are not spelled correctly:" << endl;
cout << words << endl;
cout << "Thanks for using the spell checker system." << endl;
}
}
}
file.close();
}

The error message is self-explanatory. open() in the version of C++ you are compiling for does not accept a std::string as a parameter. That overload was added in C++11.
So, either update your project to compile for C++11 or later, or else for older versions you will have to use this instead:
file.open(filename.c_str());

Related

Appending strings to text files in C++

C++ beginner here,
I am trying to append some text to a pre-written .txt file where every line there is a word.
I have been using the method ofstream and ifstream as seen below, but everytime I try to write something, it erases the file. (I am not allowed to use ios:app or simillar)
int append_new_word() {
//First I read everything on the list and save it to a string called Words_in_List
ifstream data_wordlist_in("woerterliste"); //Opens the txt file
if (!data_wordlist_in) // checks if the file exists
{
cout << "File does not exist!" << endl;
return 1;
}
string Word;
int line = 0;
string Vorhandene_Woerter;
std::getline(data_wordlist_in, Wort);
do { //line counter, goes through all lines and save it to a string
line++;
std::getline(data_wordlist_in, Word);
Words_in_List = Words_in_List + "\n" + Word;
} while (!data_wordlist_in.eof());
cout << Words_in_List << endl;
data_wordlist_in.close();
//HEre it should save the string again in the list word per word with the neu appended word
ofstream data_wordlist_out("woerterliste"); //opens ofstream
if (!data_wordlist_out)
{
cout << "File does not exist!" << endl;
return 1;
}
string new_word_in_list;
cout << "\n Insert a Word to append: ";
cin >> new_word_in_list;
data_wordlist_out << Words_in_List << endl << new_word_in_list;
data_wordlist_out.close(); //closes ofstream
}
Everytime I try I open my program it erases the list.
Your code has some minor problems, but nothing that matches your description of it.
It does line based input, which is strange because nothing in the problem description indicates that reading a line at a time is necessary.
It counts lines, again for no obvious reason.
It skips the first line (maybe this is deliberate, but if so you didn't mention that).
The loop termination is incorrect (see link in the comments).
The function is declared as returning an int but no return is made.
Here some code that addresses these problems. It reads characters not lines (using get()) which makes reading the input simpler, but essentially it's the same technique as your code.
void append_new_word()
{
string existing_content;
ifstream in("file.txt");
char ch;
while (in.get(ch))
existing_content += ch;
in.close();
cout << "enter a new word ";
string new_word;
cin >> new_word;
ofstream out("file.txt");
out << existing_content << new_word << '\n';
}

How can i open multiple files in one run in C++?

Hey I have several Files that I want to read. The user would input what file they want to open on console. And if they want they can change and read another file, they would do so.
This is how i went by doing (this is just rough copy, the code i have is too big will take too long to understand)
#include <string>
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include<algorithm>
using namespace std;
int main()
{
string FileName;
string Line;
cout << "Input File Directory To Open :" << endl;
cin >> FileName;
ifstream File;
File.open(FileName);
string Input;
do {
cout << "Enter R to Read Display Data In File Or C to Read Another File Or X To Exit" << endl;
cin >> Input;
if (Input == "R")
{
while (getline(File, Line))
{
cout << Line;
}
}
else if (Input == "C")
{
string FileName2;
cout << "Enter New File Directory To Open: " << endl;
cin >> FileName2;
//? ? ? ?
}
} while (Input != "X");
}
Since it's in do while loop, when user input C and input directory to read another file, so that they can cout new file when they input R next.
My question is how should i overwrite the FileName2 with FileName?
Hope It makes sense Thank you
First close the file that is already open:
File.close();
Then open the new one:
File.open(FileName2);
Both answers keep your idea of an open file handle. However, a better approach is to use RAII. In that case you only register the file name and only open the file when you need it.
int main()
{
std::cout << "Input File Directory To Open :\n";
std::string fileName;
std::cin >> fileName;
while (true) {
std::cout << "Enter R to Read Display Data In File Or C to Read Another File Or X To Exit\n";
std::string input;
std::cin >> input;
if (input == "X") break;
if (input == "R") {
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
std::cout << line;
}
// due to RAII the file will close when the object goes out of scope
} else if (input == "C") {
std::cout << "Enter New File Directory To Open: \n";
std::cin >> fileName;
}
}
}
You don't need a new variable. Simply assign the value to the existing one, close the currently opened file, and then open the new file inside the loop:
...
else if (Input == "C")
{
cout << "Enter New File Directory To Open: " << endl;
cin >> FileName;
File.close();
File.open(FileName);
}
...

Using I/O streams to read from one file and write to another

I'm going through a text-book where an exercise entails copying text from one file and write it's lower-case equivalent to another file. I can't seem to find a way to do that using just I/O streams (most of the solutions I found online use stream buffers).
My code is this
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi.get(ch)) {
fs2 << ch;
}
After running nothing is written to the second file (f_name2). It's just a blank file.
Edit:
This doesn't work either
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1>>f_name2;
ofstream fs{ f_name1 };
ifstream fsi{f_name1};
ofstream fs2{f_name2};
fs << "LoRem ipSUM teXt TaXi";
char ch;
while (fsi>>ch) {
fs2 << ch;
}
}
You are complicating your task for no apparent gain. There is no need for
ofstream fs{ f_name1 };
fs << "LoRem ipSUM teXt TaXi";
Use a text editor and create the contents of the input file outside the program.
Here's an updated version of your main fuction:
int main()
{
string f_name1, f_name2;
cout << "enter the file names" << '\n';
cin >> f_name1 >> f_name2;
ifstream fs1{f_name1};
if ( !fs1 )
{
std::cerr << "Unable to open " << f_name1 << " to read from.\n";
return EXIT_FAILURE;
}
ofstream fs2{f_name2};
if ( !fs2 )
{
std::cerr << "Unable to open " << f_name2 << " to write to.\n";
return EXIT_FAILURE;
}
// Using ostream::put() seems the right function to use
// for writing when you are using istream::getc() for reading.
char ch;
while (fs1.get(ch))
{
fs2.put(std::tolower(ch));
}
}
Hmm. So you're writing to the file and then reading the contents and writing out again. Okay...
You might need to fs.flush() after the fs << code. The data can be buffered, waiting for a newline character to trigger a flush, or doing one yourself.
I'd also put in some print statements in your while loop to make sure you're getting what you think you're getting.

I'm working on reading and writing to files with c++

Hi guys I'm working on my last assignment of the computer science class. I think I'm doing everything fine but something is wrong. Can you take a look at it and tell what I'm doing wronger here.
here is what I get when I try to submit online on zybooks site:
"Your program produced no output"
Expected:
Ryan Hermle
22.99
Lochness Monster
3.50
Wonder Woman
123456.78
here are instructions from professor:
Constructor:
Takes a string parameter and stores that as fileName. Does not need to do anything else.
append:
Takes a record as a parameter that contains a string and a double
Open an output file stream in append mode using fileName
set its precision to 2 and fixed
Output the name, newline, the money, newline
searchName:
Open an input file stream with fileName
Loop while a getline and a double extraction are successful
if the string parameter is equal to the name read from the getline, then return the double
If the loop finishes without finding anything, return -1 to indicate that name was not found.
getData:
Open an input file stream with fileName
Construct an ostringstream
Set its precision to 2 and fixed
Loop while a getline and a double extraction are successful
ignore the \n left by the >> extraction
write the string, newline, double, newline to the ostringstream
return the string contained by the ostringstream
here is my main:
#include "Database.h"
int main()
{
Database db("data.txt");
db.append(Record{"Ryan Hermle", 22.99});
db.append(Record{"Lochness Monster", 3.50});
db.append(Record{"Wonder Woman", 123456.78});
}
and here is my Database.cpp file:
#include "Database.h"
Database::Database(string file)
{
fileName = file;
}
void Database::append(Record data)
{
ofstream out;
out.open(fileName, ios::app);
out << setprecision(2) << fixed;
cout << data.name << endl;
cout << data.money << endl;
out.close();
}
double Database::searchName(string n)
{
Record s;
ifstream in;
in.open(fileName);
while (getline(in, n) >> s.money)
{
in.ignore();
if (n == s.name)
{
return s.money;
}
}
return -1;
}
string Database::getData()
{
Record s;
ifstream ifs;
ifs.open(fileName);
ostringstream oss;
oss << setprecision(2) << fixed;
while(getline(ifs, s.name) >> s.money)
{
ifs.ignore();
oss << s.name << endl << s.money << endl;
cout << oss.str();
}
return oss.str();
}
Thanks for everyone who replied to my post. I was able figure out the error in my program.
The error was in append Function:
cout << data.name << endl;
cout << data.money << endl;
It should be like this:
out << data.name << endl;
out << data.money << endl;

regarding: instance of 'std::bad_alloc'

I read other posts but none of them helping at all,
This code have no error still there is bad_alloc error...
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "\n\nReading from file \n\n" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
This code is terminating after coming to sentence statement..the getline() function is causing problem i guess but when i tried on other two statements(name and last_name),the getline(), it works perfectly..i even degraded the char limit to 5 too but after sentence statement is throw anyways
Thumb rule, don't fool yourself into thinking that your code has no errors. Especially when you clearly got an error. This kind of mindset will make you unable to find errors because everything you see is correct.
You never checked if your streams were open and you entered the wrong file name in the ofstream.
What happens is that, you write your data into a file name farses.dat and then you try to open a file called frases.dat (which I assume is the correct name, it means sentences).
You are getting the cursor position ifstream::tellg of an inexistent file, and it fails so the function returns -1. This is the value of length before you allocate your buffer.
When you do allocate your buffer you get a bad_alloc exception (bad_array_new_length).
Checking if your file was open would, at the very least, have saved you some debug time.
Something like this,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
EDIT: Fixed error explanation.