C++ ifstream error using string as opening file path - c++

I get this error when I try running the program.What might be the problem as the code is correct as far as I can see.
Here is the error
std::basic_fstream::basic_fstream(std::string&, const openmode&)'
Here is the code
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string fileName;
int frequencyArray[26];
char character;
for (int i = 0; i < 26; i++)
frequencyArray[i] = 0;
cout << "Please enter the name of file: ";
getline(cin, fileName);
fstream inFile(fileName, fstream::in); // to read the file
if (inFile.is_open())
{
while (inFile >> noskipws >> character)
{
// if alphabet
if (isalpha(character))
{
frequencyArray[(int)toupper(character) - 65]++;
}
}
inFile.close();
cout << "Letter frequencies are as: " << endl;
for (int i = 0; i < 26; i++)
{
cout << (char)(i + 65) << " = " << frequencyArray[i] << endl;
}
}
else
{
cout << "Invalid File. Exiting...";
}
return 0;
}

You could change
fstream inFile(fileName, fstream::in);
to
fstream inFile(fileName.c_str(), fstream::in);

Although C++11 defines a std::fstream constructor that accepts a std::string as input, Microsoft's implementation of std::fstream apparently does not:
https://msdn.microsoft.com/en-us/library/a33ahe62.aspx#basic_fstream__basic_fstream
You will have to use the std::string::c_str() method to pass the filename:
fstream inFile(fileName.c_str(), fstream::in);
That being said, consider using std::ifstream instead:
ifstream inFile(fileName.c_str());

Related

Read input from a file, capitalize first letter, make every other letter lowercase, and output into a separate file

I am supposed to ask the user for two file names (input and output files). The contents from the input file should be read and the first letter of each sentence should be made uppercase while every other letter should be made lowercase. The results should then be stored in the output file.
I am aware that there are ways of using the toupper and tolower functions that include pointers, arrays, or even ASCII values of chars but I am trying to get this code to work by using if/else and while statements, as well as boolean statements. I have had various results ranging from all the letters being capitalized to none of the letters being capitalized however, I think right now I am on the right track with the code and am just overlooking the way I am incrementing through the characters causing the code to not capitalize after a period and a space.
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string input_file; // To hold input file name
string output_File; // To hold output file name
char ch; // To hold character
fstream inputFile;
fstream outputFile;
bool new_sentence = true;
cout << "Enter input file name: " << endl;
cin >> input_file;
cout << "Enter output file name: " << endl;
cin >> output_File;
outputFile.open(output_File, ios::out);
inputFile.open(input_file, ios::in);
if (inputFile) {
while (inputFile.get(ch)) {
if (isprint(ch)) {
if (new_sentence) {
outputFile.put(toupper(ch));
}
else {
outputFile.put(tolower(ch));
}
new_sentence = false;
}
else {
if (ch == '.') {
new_sentence = true;
outputFile.put(ch);
}
}
}
inputFile.close();
outputFile.close();
}
else {
cout << "Cannot open file(s)." << endl;
}
cout << "\nFile conversion complete." << endl;
return 0;
}
With my current code I am able to capitalize the first letter of the first sentence and make every other letter lowercase. I am able to store and show the results in the output file. My issue is that the first letter of every other sentence after the first one won't change to uppercase. This makes me think the issue is in this part of the code:
if (new_sentence)
{
outputFile.put(toupper(ch));
}
else
{
outputFile.put(tolower(ch));
}
Am I missing something here?
You have a minor logical error.
You first need to check, if the character is a period. This state you need to remember. If then a next character isalpha, then we check, if recently the newsentence flag has been set. In this case, and only in this case, we reset the new sentence flag and convert the character to uppercase.
All other alpha characters will be converted to lowercase. Other charcaters will not be converted.
In your solution you always reset the newsentence flag. Even, if the next print character is a space (Which is most liekly the case).
Please see updated solution:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string input_file; // To hold input file name
string output_File; // To hold output file name
char ch; // To hold character
fstream inputFile;
fstream outputFile;
bool new_sentence = true;
cout << "Enter input file name: " << endl;
cin >> input_file;
cout << "Enter output file name: " << endl;
cin >> output_File;
outputFile.open(output_File, ios::out);
inputFile.open(input_file, ios::in);
if (inputFile) {
while (inputFile.get(ch)) {
if (ch == '.') {
new_sentence = true;
}
if (isalpha(ch)) {
if (new_sentence) {
ch = toupper(ch);
new_sentence = false;
}
else {
ch = tolower(ch);
}
}
outputFile.put(ch);
}
inputFile.close();
outputFile.close();
}
else {
cout << "Cannot open file(s)." << endl;
}
cout << "\nFile conversion complete." << endl;
return 0;
}
And then, please see some further improvements:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
int main() {
// Will hold the input and output filename
std::string filename;
// This is our flag to indicate that a new sentence will come
bool newSentence = true;
// Get input filename
std::cout << "Enter input file name: " << "\n";
std::cin >> filename;
// And try to open the file
std::ifstream inFile(filename);
std::cout << "Enter output file name: " << "\n";
std::cin >> filename;
// And try to open the file
std::ofstream outFile(filename);
// Only convert, if the input and output file could be opened
if (inFile && outFile) {
char ch;
while (inFile.get(ch)) {
if (ch == '.') {
newSentence = true;
}
if (isalpha(ch)) {
if (newSentence) {
ch = toupper(ch);
newSentence = false;
}
else {
ch = tolower(ch);
}
}
outFile.put(ch);
}
}
else {
std::cout << "Cannot open file(s)\n";
}
std::cout << "\nFile conversion program complete\n";
return 0;
}
And the full blown "C++ with algorithm" solution. Here the conversion, or transformation is done in one statement
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <algorithm>
#include <iterator>
int main() {
// Will hold the input and output filename
std::string filename;
// Get input filename
std::cout << "Enter input file name: " << "\n";
std::cin >> filename;
// And try to open the file
std::ifstream inFile(filename);
std::cout << "Enter output file name: " << "\n";
std::cin >> filename;
// And try to open the file
std::ofstream outFile(filename);
// Only convert, if the input and output file could be opened
if (inFile && outFile) {
// Do the conversion
std::transform(
std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(outFile),
[newSentence = true](char c) mutable {
if (c == '.') newSentence = true;
if (std::isalpha(c))
if (newSentence) {
newSentence = false;
c = std::toupper(c); }
else c = std::tolower(c);
return c;
}
);
}
else {
std::cout << "Cannot open file(s)\n";
}
std::cout << "\nFile conversion program complete\n";
return 0;
}
But if the last solution adds additional value? I am not sure . . .
This part of your code should be changed:
// if (isprint(ch)) {
if (ch != '.') {
if (new_sentence) {
outputFile.put(toupper(ch));
}
else {
outputFile.put(tolower(ch));
}
new_sentence = false;
}
else {
new_sentence = true;
outputFile.put(ch);
}
std::isprint() only checks if the character is printable.
Full code:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string input_file; // To hold input file name
string output_File; // To hold output file name
char ch; // To hold character
fstream inputFile;
fstream outputFile;
bool new_sentence = true;
cout << "Enter input file name: " << endl;
cin >> input_file;
cout << "Enter output file name: " << endl;
cin >> output_File;
outputFile.open(output_File, ios::out);
inputFile.open(input_file, ios::in);
if (inputFile) {
while (inputFile.get(ch)) {
if (ch != '.') {
if (new_sentence) {
outputFile.put(toupper(ch));
}
else {
outputFile.put(tolower(ch));
}
new_sentence = false;
}
else {
new_sentence = true;
outputFile.put(ch);
}
}
inputFile.close();
outputFile.close();
}
else {
cout << "Cannot open file(s)." << endl;
}
cout << "\nFile conversion complete." << endl;
return 0;
}

How to write in the same file C++

I need to delete all the occurencies of a string in a file.
I receive the text as a string and erase every occurencies.
After I deleted all the occurencies i don't know how to save the string back to the file.
I've tried to close the file and wit ofstream to write in it but it didn't work.
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::string file_contents = "";
std::ifstream myfile ("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while ( myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
std::string::size_type found;
std::string new_text;
//DELETE WORD FROM STRING
bool ok=0;
do{
found = file_contents.find(word);
ok=1;
if (found!=std::string::npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
else
ok==0;
new_text=file_contents;
}while(ok==1);
myfile.close();
}
else std::cout << "Unable to open file";
return 0;
}
Okay so you must close ifstream instance before proceeding to write to the file again.
After closing the file, modify the content and then open the same file for write using ofstream and simply write the content.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string file_contents = "";
std::ifstream myfile("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while (myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
myfile.close();
}
else {
std::cout << "Unable to open file";
return -1; // no need to continue if can't read it
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
//DELETE WORD FROM STRING
size_t found;
while ((found = file_contents.find(word)) != file_contents.npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
// this will open in text mode and will replace all existing content
std::ofstream out("text.txt");
if (out.is_open()) {
out << file_contents;
out.close();
}
else {
std::cout << "Unable to open file for writing.\n";
return -2; // for failure to open for write
}
return 0;
}
Note: the loop you had went infinitely when I tried to execute it, I had to change it to the code shown above. Also, new_text is completely unnecessary, why have it?
The simpliest way is first to open as input stream. When finish open as output stream to write. It is not the only way you can do that.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
std::string file_contents = "";
{
std::ifstream myfile ("text.txt");
if (! myfile.is_open())
{
else std::cout << "Unable to open file";
return 1;
}
// READ FILE CONTENTS AS STRING
char ch;
while ( myfile >> std::noskipws >> ch) file_contents += ch;
myfile.close();
}
{
std::string word;
std::cin >> word; // GET WORD TO BE DELETED
std::string::size_type found;
while((found = file_contents.find(word))!=std::string::npos)
file_contents.erase(found, word.length());
std::ofstream myfile ("text.txt");
myfile << file_contents<< std::flush;
myfile.close();
}
return 0;
}

Where did I go wrong in my code for word count C++

#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
void wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0,i;
char next,last[1];
in_stream.get(next);
while (!in_stream.eof())
{
if (next == ' ')
(next >> last[1]);
for(i = 0; last[i] != '\0'; ++i)
{
if (last[i] == ' ')
counter++;
}
in_stream.get(next);
}
}
I'm trying to get the word count of this and its not working
the chars being saved are fine, but whats not working if I input from notepad a file with something like:
I
am
working
it will show 0 words if I I type normally it will count the words why is that?
I edit your code, Do you mean something like this?
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int wordCount(ifstream& in_stream, ofstream& out_stream);
int main()
{
char inputFile[100];
ifstream fin;
ofstream fout;
cout << "Enter a File name: " << endl;
cin >> inputFile;
fin.open(inputFile);
if (fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
int WordCount = wordCount(fin, fout);
fin.close();
fout.close();
return 0;
}
int wordCount(ifstream& in_stream, ofstream& out_stream)
{
int counter = 0;
char data[100];
in_stream >> data;
while (strlen(data)>0)
{
counter++;
in_stream >> data;
}
return counter;
}

get() function in c++ not working for files

I wrote the following code in codeblocks and since I am new to programming I would like to know the problem in simple words. Does the open() constructor create a new file if it does not exists?
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char str[80];
cout<<"Enter a string : ";cin>>str;
int len=strlen(str);
fstream file;
file.open("TEXT",ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(str[i]);
file.seekg(0);
char ch;
cout<<"\nPrintitng Contents....\n";
int k=0;
while(file)
{
file.seekg(k);
file.get(ch);
cout<<ch;
k++;
}
return 0;
}
I think you don't have "TEXT". and fstream::open don't make file when if file that you want to read do not exist.
so you may try in different stream to read and write.
following code will help you.
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string : ";
cin >> str;
int len = strlen(str);
ofstream fout;
fout.open("TEXT.txt");
for (int i = 0; i<len; i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("TEXT.txt");
char ch;
cout << "\nPrintitng Contents....\n";
while (!fin.eof())
{
fin.get(ch);
cout << ch;
ch = NULL;
}
fin.close();
return 0;
}
and you may improve your code like this
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Enter a string : ";
cin >> str;
ofstream fout;
fout.open("TEXT.txt");
fout << str;
fout.close();
str.clear();
ifstream fin;
fin.open("TEXT.txt");
cout << "\nPrintitng Contents....\n";
fin >> str;
cout << str;
fin.close();
return 0;
}
Following code is more appropriate for C++, I think
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string str;
string newStr;
cout << "Enter a string : "; cin >> str;
int len = str.length();
fstream file;
file.open("TEXT", ios::out| ios::in );
if (!file.is_open())
return 0;
file << str;
file.seekg(0,file.beg);
char ch;
cout << "\nPrintitng Contents....\n";
file >> newStr;
cout << newStr;
file.close();
return 0;
}

How to detect a new line and add it to the string. Fstream

Hello I created this program and the only problem is I don't know how to detect a new line and how to add \n to the string every time new line occurs. I'm using Visual Studio Community 2015 if it matters. Thank you!
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ofstream ofile;
ifstream ifile;
string filehold;
vector<string> data;
string line;
ofile.open("C:/Users/Nada/Desktop/data.txt");
ofile << "ph4n70m is awesome \n LOL im awesome"<< flush;
ifile.open("C:/Users/Nada/Desktop/data.txt");
if (ifile.fail()) {
cerr << "Error!" << endl;
system("pause");
exit(1);
}
while (!ifile.eof()) {
ifile >> filehold;
data.push_back(filehold);
}
cout << "data.txt: " << endl;
for (unsigned int i = 0; i < data.size(); i++) {
cout << data[i] + " ";
}
ifile.close();
system("pause");
return 0;
}
Change your reading loop to
while (std::getline(ifile,filehold)) {
filehold += '\n';
data.push_back(filehold);
}