ofstream not properly naming created files - c++

this does create a file like i want but instead of the input name it just calls it fileName and it doesn't have a type. Its supposed to take an input of something like "story.txt" and create a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string userInput;
string endWrite = "** STOP **";
string fileName = "";
cin >> fileName;
ofstream storyTime(fileName.c_str());
storyTime.open("fileName");
if (!storyTime.is_open()) {
cout << "Could not open file " << fileName << "." << endl;
return 1;
}
getline(cin, userInput);
while (userInput != endWrite) {
storyTime << userInput << endl;
getline(cin, userInput);
}
storyTime.close();
return 0;
}

Related

C++ writing content of a vector to a txt class?

So I made a function that reads lines from two files and writes them to a vector. Called the function twice, once for each of the files. Now how should I go for writing the content of the vector to a new file? Also, am I doing it correctly?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
bool getFile(string filename, vector<string> & vecOfStrs){
ifstream in(filename.c_str());
if (in.fail()) {
cout << "No such file" << "\n";
return 1;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
vecOfStrs.push_back(str);
}
in.close();
return true;
}
int main(){
vector<string> A;
string lecCourse;
cout << "First file: ";
cin >> lecCourse;
string lab_ex;
cout << "Second file: ";
cin >> lab_ex;
string exit;
cout << "Name of exit file: " << "\n";
cin >> exit;
bool result = getFile(lecCourse, A);
bool result2 = getFile(lab_ex, A);
ofstream output;
output.open(exit.c_str());
if (output.fail()) {
cout << "error" << "\n";
return 1;
}
}
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
vector<string> A;
bool getFile(string filename, vector<string> & vecOfStrs){
ifstream in(filename.c_str());
if (in.fail()) {
cout << "No such file" << "\n";
return 1;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
vecOfStrs.push_back(str);
}
in.close();
return true;
}
int main()
{
string lecCourse;
cout << "First file: ";
cin >> lecCourse;
string lab_ex;
cout << "Second file: ";
cin >> lab_ex;
string exit;
cout << "Name of exit file: " << "\n";
cin >> exit;
bool result = getFile(lecCourse, A);
bool result2 = getFile(lab_ex, A);
ofstream output;
output.open(exit.c_str());
for(int i=0;i<A.size();i++)
{
output<<A[i]<<"\n";
}
if (output.fail()) {
cout << "error" << "\n";
return 1;
}
}
Hope!!
This might helps:))

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;
}

C++ reading from a .txt file line by line string and number data type on each line

So I am trying to read a .txt file in c++ program. Each line in the text file has firstName, lastName and yearlySalary (e,g, Tomm Dally, 120000).
I can seem to read a file properly - it skips the first column (firstName) and stops reading the data in after first line. Why is that?
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
double backPayDue;
double newAnualSalary;
double newMonthlyWage;
int numOfEmployees = 0;
double totalBackPayDue = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (!empSalariesOld.fail())
{
while (empSalariesOld >> fName)
{
empSalariesOld >> fName >> lName >> yearlyPay;
std::cout << fName << " " << lName << " " << yearlyPay << endl;
numOfEmployees++;
}
}
empSalariesOld.close();
empSalariesNew.close();
system("pause");
return 0;
}
You are not reading the lines correctly.
When your while statement calls empSalariesOld >> fName for the first time, it reads an employee's first name. Then, inside the loop body, when you call empSalariesOld >> fName >> lName >> yearlyPay, >> fName reads the employee's last name (because you already read the first name), then >> lName reads the employee's salary, and >> yearlyPay tries to read the next employee's first name and fails!
Try something more like the following instead. Use std::getline() to read a whole line, and then use std::istringstream to parse it:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (iss >> fName >> lName >> yearlyPay) {
std::cout << fName << " " << lName << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}
However, if the lines actually have a comma between the name and salary like you showed (Tomm Dally, 120000), then try the following instead:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string name;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (getline(iss, name, ',') && (iss >> yearlyPay))
std::cout << name << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}

I'm only able to input one word into the file

Like my title said, I am having problems with file input.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void CreateNewFile(const string FileName) {
ofstream NewFile;
string FileNamePlaceholder = FileName + ".txt";
NewFile.open(FileNamePlaceholder);
cout << "What would you like to write to the file? ";
string InputForFile;
cin >> InputForFile;
NewFile << InputForFile;
NewFile.close();
cout << "You will now be able to view the file in your computer.\n";
}
void Start() {
char NewFile;
cout << "Would you like to create a new file? [Y/N] ";
cin >> NewFile;
if (NewFile == 'y' || NewFile == 'Y') {
cout << "What would you like the new file to be named? ";
string NewFileName;
cin >> NewFileName;
CreateNewFile(NewFileName);
}
else if (NewFile == 'n' || NewFile == 'N') {
cout << "Ok, bye.\n";
}
else {
cout << "You did not type y, Y, n, or N!\n";
}
}
int main(void) {
Start();
return 0;
}
For some reason, I can only input one word at a time into the file. I'm sorry if this is an obvious answer. Any help would be appreciated.

input/output for a file in c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Main Routine
void main() {
char in;
string s,m;
fstream f;
// Open file
cout << "Positive Filter Program\n"<< endl;
cout << "Input file name: ";
cin >> s;
cout << "Output file name: ";
cin >> m;
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
// Loop through file
if(f.is_open())
{
while(f.good())
{
f.get(in);
f<<in;
cout << "\nFinished!"<< endl;
}
}
else cout << "Could not open file";
// Close file
f.close();
}
I am not sure what I am doing wrong here. In this program I am trying to cin the file name that would input, and then would output onto what file name that you typed in.
The same fstream object is being reused:
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
it will never read the input file. Change to:
std::ifstream in(s.data());
std::ofstream out(m.data());
The while loop is incorrect, the result of a read attempt should be checked immediately after the read:
char ch;
while(in.get(ch))
{
out << ch;
}
cout << "\nFinished!"<< endl; // Moved this to outside the while