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

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.

Related

ofstream not properly naming created files

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

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

Accessing Variable values from another file c++

I am doing something that requires a password.
right now I am able to create files and store custom user input in that but I cant seem to find anywhere how to store a variable with the user created value, and make it so that the next time the program starts it will be able to read that file and understand the value.
#include "stdafx.h"
#include "string"
#include "iostream"
#include "fstream"
#include "windows.h"
using namespace std;
int main() {
string user;
string pass;
string entry;
std::ifstream f("test.txt");
if (f.fail()) {
std::ofstream outfile("test.txt");
cout << "Please make a username.\n";
cin >> user;
cout << "Please make a password.\n";
cin >> pass;
outfile << user << std::endl;
outfile << pass << std::endl;
outfile.close();
cout << "Please restart.\n";
int x = 3000;
Sleep(x);
}
else {
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
return 0;
}
You haven't added the necessary code to read the saved user name and password. In the else part of the function, add
f >> user;
f >> pass;
as the first two lines.
else {
// Read the user name and password from the file.
f >> user;
f >> pass;
cout << "please enter username\n";
cin >> entry;
if (entry == user) {
cout << "Welcome";
int x = 3000;
Sleep(x);
}
else if (entry != user) {
cout << "Nope";
int x = 3000;
Sleep(x);
}
}
You can use string::find function to search your string in a file after ifstream.
if (string1.find(string2) != std::string::npos)
{
std::cout << "found\n";
}
else
{
std::cout << "not found\n";
}

C++ Program crashes while reading from file using fstream fin

Final project for programming class due tomorrow, any help appreciated, program crashes in this module, after accepting file name. By crash I mean it outputs "This application has requested runtime to terminate it in an unusual way" and then the usual windows "CotD.exe has stopped working":
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
while (!fin.eof())
{
Fish f;
string blank;
fin >> f.amt;
fin >> f.prc;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(fin, blank);
stock.push_back(f);
}
fin.close();
break;
}
} while (true);
}
EDIT other relevant code:
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;
//
string file = "default.txt"; //Global variable used to store name of save file.
//It is global so that load() and save() can both access it.
struct Fish
{
string type;
double amt;
double prc;
double val;
};
void addType(vector<Fish>&);
void editStock(vector<Fish>&);
void sortBy(vector<Fish>&);
void sortAsc(vector<Fish>&,char);
void sortDesc(vector<Fish>&,char);
void display(vector<Fish>&);
int search(vector<Fish>&);
void save(vector<Fish>&);
void load(vector<Fish>&);
string getType();
int dispType(string,vector<Fish>&);
int find(string,vector<Fish>&);
double getAmt();
void delType(string,vector<Fish>&);
void menu(vector<Fish>&);
double getPrc();
int main(){
std::vector<Fish> stock;
load(stock);
menu(stock);
save(stock);
cout<<endl<<endl
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
<<"|Thank you for using Catch of the Day|\n"
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
system("Pause");
return 0;
}
I recently wrote this program which seems very similar to me, and ran perfectly I can't see the difference:
void load(vector<string>& names)
{
string file, name, bad;
while (true)
{
cout << "Input file name\n";
getline(cin, file);
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << ", try again.\n";
}
else break;
}
ifstream fin(file.c_str());
while (!fin.eof())
{
fin >> bad;
fin >> name;
cout << "\"" << name << "\"" << endl;
}
system("Pause");
fin.close();
ifstream fin(file.c_str());
while (!fin.eof())
{
getline(fin, name);
names.push_back(name);
}
system("Pause");
fin.close();
cout << "Names added to list\n";
}
I've edited your code, this is what I got:
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
Fish f;
string blank;
if (fin>>f.amt)
{
if (fin>>f.prc)
{
getline(fin,blank);
stock.pushback(f);
}
}
fin.close();
break;
}
} while (true);
}
Of course, this is without knowing what is in the file and what the heck Fish is, so I do not know if this is what you are looking for.
EDIT:If you could include the file, or just a section of one "fish" as I assume that is what the contents of the file are, it would be alot easier to help.

C++: Save information from console, then when reopened, information is still there

I have a program that saves your favorite games for you onto a list. How would I make it so that if I close the console and reopen it, the list is still there, and all the elements in the array are saved?
using namespace std;
int main()
{
vector<string> games;
vector<string>::iterator iter;
while(true)
{
system("cls");
string response;
cout << "\tFavorite Videos Games \n\n";
cout << "Type 'add' to add a game.\n";
cout << "Type 'remove' to remove a game.\n";
cout << "Type 'list' to list all games.\n\n";
cout << "Type 'quit' to close and save the program.";
cout << "What would you like to do: ";
cin >> response;
cout << endl;
if ((response == "add") || (response == "remove") || (response == "list"))
{
int number;
string gameName;
if(response == "add")
{
cout << "What is the name of the game you would like to add?\n";
cout << "Name: ";
cin >> gameName;
games.push_back(gameName);
cout << gameName << " was added to the system.\n\n";
Sleep(2000);
continue;
}
if(response == "remove")
{
vector<string>::iterator linesIn;
int spacesIn;
cout << "What game should be deleted?\n\n";
cout << "All Games:\n-----------\n";
for(iter = games.begin(); iter != games.end(); ++iter)
{
number ++;
cout << number << ". " << *iter << endl;
}
cout << "Number: ";
cin >> spacesIn;
spacesIn = spacesIn -1;
linesIn = games.begin() + spacesIn;
cout << *linesIn << " was deleted.";
games.erase(linesIn);
Sleep(2000);
}
if(response == "list")
{
cout << "All Games:\n-----------\n";
for(iter = games.begin(); iter != games.end(); ++iter)
{
number ++;
cout << number << ". " << *iter << endl;
}
cout << "\n\nPress any key to continue...";
getch();
}
}
else if (response == "quit")
break;
else
{
cout << "\nInvalid action.\n\n";
Sleep(2000);
continue;
}
}
return 0;
}
The easiest way would be to save it out to file.
Example from http://www.cplusplus.com/doc/tutorial/files/:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Perhaps add another option called save, and just iterate through the games and add them to a file called "mygames.txt."
Then add an option called "load saved games" and do something like:
string line;
ifstream myfile ("example.txt");
if (myfile.is_open()){
while ( getline (myfile,line) ){
games.push_back(line);
}
myfile.close();
Obviously, these are just examples, but I feel it is clear enough that you can take it form here.
Save the information to file.
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
else if ( response == "quit") {
std::ofstream f( "list.txt");
if( !f) return -1;
std::vector<std::string> games;
std::copy( std::istream_iterator<std::string>(f), // copy file content
std::istream_iterator<std::string>(), games.begin()); // to vector
}
On the start of program:
int main()
{
std::ifstream f( "list.txt");
if( !f) return -1;
std::copy( istream_iterator<std::string > (f), // copy file content to vector
std::istream_iterator<std::string > (), std::back_inserter(games));
//...
Complete example:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main( int argc, char** argv) {
fstream f;
f.open( "list.txt", std::ios::in);
if (!f) return -1;
vector<string> games;
copy( istream_iterator<string > (f), // copy file content to vector
istream_iterator<string > (), back_inserter(games));
f.close();
string response;
while ( 1) {
cin >> response;
if ( ( response == "a")) {
int number; string gameName;
cout << "What is the name of the game you would like to add?\n";
cout << "Name: "; cin >> gameName;
games.push_back(gameName);
cout << gameName << " was added to the system.\n\n";
} else if ( response == "q") {
f.open( "list.txt", std::ios::out);
if ( !f) return -1;
copy( games.begin(), games.end(), // copy from vector to a file
ostream_iterator<string > ( f, "\n"));
f.close();
return 0;
}
}
}