I would like to write the words in the file until I type the word "stop", but only the first word is saved to the file.
What's the problem?
int main(int i)
{
ofstream file;
string file_name,message;
cout << "\nFilename: ";
cin >> file_name;
cout << "Write 'stop' to end writig to file" << endl;
for(i=0; message!="stop"; i++)
{
cout << "\nYour message: ";
cin >> message;
file.open(file_name.c_str());
file << message.c_str() << "\t" ;
}
file.close();
return 0;
}
It should be,
int main()
{
int i;
ofstream file;
string file_name,message;
cout << "\nFilename: ";
cin >> file_name;
cout << "Write 'stop' to end writig to file" << endl;
file.open(file_name.c_str());
for(i=0; message!="stop"; i++)
{
cout << "\nYour message: ";
cin >> message;
if(message == "stop"){ //If you dont want word stop
break;
}
file << message.c_str() << "\t" ;
}
file.close();
return 0;
}
It would be better if you do something like,
do{
//do stuff
if (message == "stop")
break;
}while(message != "stop");
In this case, you better switch to a while loop of the form: while (!file.eof()), or while (file.good()).
Apart from that, the for loop has to define the variable, in your case i is undefined, and must contain the range of the variable and no other variable definition (condition on message must not be inside it. It has to be an if condition inside the for loop).
...
char word[20]; // creates the buffer in which cin writes
while (file.good() ) {
cin >> word;
if (word == "stop") {
break;
...
}
}
...
Actually, I am not sure how it compiles at all in your case :) For future reference: for loop should look like this: for (int i = 0; i<100; i++) {};
I hope it is clear!
Related
So I am working on a switch inside of a while loop. And it is not behaving properly. When I select 'l' and load the file it lets me select again, then when I try and press 'p' to print it, it just keeps looping over the selection prompt. I am pretty sure it is because choice != 'q', but don't know how to fix it.
Thank you for any help.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//create a struct called Weather
struct Weather {
int month;
int date;
int high;
int avg;
int low;
double precip;
string event;
};
//function prototypes
int loadData(ifstream &file, Weather days[1000]);
void printData(Weather days[1000], int count);
int main() {
// declare variables
Weather days[1000];
ifstream inFile;
string checker;
char choice = '0';
int month = 0, count;
string path;
cout << "Welcome to the weather analyzer!" << endl;
while (choice != 'q') {
cout << "Would you like to (l)oad data, (p)rint data, (s)earch data, (o)rder the data, or (q)uit? ";
cin >> choice;
cout << endl;
switch (choice) {
case 'l':
// promt user for file path
cout << "Please enter the file path: ";
cin >> path;
// open the file
inFile.open(path);
// checks to see if file successfully opened and terminates if not
if (!inFile) {
cout << "Bad Path";
getchar();
getchar();
return 0;
}
loadData(inFile, days);
count = loadData(inFile, days);
break;
case 'p':
printData(days, count);
break;
case 's':
case 'o':
case 'q':
cout << "Good bye!";
break;
default:
cout << "Invalid option";
}
}
// Close file.
inFile.close();
// Pause and exit.
getchar();
getchar();
return 0;
}
//loading function
int loadData(ifstream &inFile, Weather days[1000]) {
string checker;
int month = 0;
int i; //i varaiable keeps track of how many lines there are for the print function
for (i = 0; !inFile.eof(); i++) {
inFile >> days[i].date; // gets date and checks if it is 2017 with if loop
if (days[i].date == 2017) {
getline(inFile, checker);
getline(inFile, checker);
inFile >> days[i].date; //gets correct date value
month++;//increments month counter
}
days[i].month = month;//gets and stores data from file into days
inFile >> days[i].high
>> days[i].avg
>> days[i].low
>> days[i].precip;
getline(inFile, days[i].event);
}
return i; //returns amount of days
}
// printing function
void printData(Weather days[1000], int count) {
for (int i = 0; i < count; i++) {
cout << days[i].month << " "
<< days[i].date << " "
<< days[i].high << " "
<< days[i].avg << " "
<< days[i].low << " "
<< days[i].precip << " "
<< days[i].event << " ";
cout << endl;
}
}
After reading the user input with cin, you probably want to flush the cin buffer:
cin.clear();
cin.ignore(INT_MAX);
I am having an issue when trying to use a getline command where a user can enter in a movie and then add to the collection of movies (stored in "movies.txt")
My code is compiling, but it starts out with the 3rd case automatically. When I press "q" to quit that case, it reverts to the menu, yet when I try and write out the file or print the collection, no movie titles have been saved. Where I should go from here? I feel like I'm on the cusp of understanding this.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int ARRAY_SIZE = 200;
string movieTitle [ARRAY_SIZE];
int loadData (string pathname);
int writeData (string pathname);
int getTitle (string movieTitle[]);
void showAll (int count);
int main()
{
loadData("movies.txt");
char userInput;
string movieTitle[ARRAY_SIZE];
int count = getTitle(movieTitle);
bool endOfProgram = false;
while (endOfProgram ==false)
{
cout << "1. Read in Collection" << endl;
cout << "2. Print Collection" << endl;
cout << "3. Add a Movie to the Collection" << endl;
cout << "4. Write out Collection" << endl;
cout << "5. Quit the Program" <<endl;
cin >> userInput;
switch(userInput)
{
case('1'):
{
loadData("movies.txt");
break;
}
case('2'):
{
showAll(loadData("movies.txt"));
break;
}
case('3'):
{
cout << getTitle(movieTitle);
break;
}
case('4'):
{
cout <<"Write out Collection" << endl;
writeData("movies.txt");
break;
case('5'):
{
endOfProgram=true;
cout << "Have a nice day" <<endl;
break;
}
}
}
}
}
int loadData (string pathname)
{
int count = 0;
ifstream inFile;
inFile.open(pathname.c_str());
if (!inFile)
return -1;
else
{
while(!inFile.eof())
{
getline(inFile, movieTitle[count]);
count++;
}
}
return count;
}
int writeData (string pathname)
{
ofstream outfile;
outfile.open("movies.txt");
if(!outfile.is_open())
{
cout << "Cannot open movies.txt" << endl;
return -1;
}
outfile.close();
return 0;
}
void showAll (int count)
{
cout << "\n";
for (int i=0; i< count; i++)
{
cout << movieTitle[i] << endl;
}
cout << "\n";
}
int getTitle (string movieTitle[])
{
string movie;
int count = 0;
while(true)
{
cout <<"Enter Movie Titles (Type 'q' to quit)" <<endl;
cin >> movie;
if (movie == "q")
{
break;
}
movieTitle [count] = movie;
count++;
}
return count;
}
I believe cin reads until eol is found, i.e. the user presses return.
So look for integer in the userInput variable, and pass that to your switch statement
int nr = atoi(userInput.c_str())
switch(nr){
case 1:
case 2: etc ...
In your codes it is not clear why it directly goes to case '3'. It should wait for a user input first. Seems like something already available in buffer. Just put one cout statement in case '3': and check what it print. If possible put break point there and run the application in debug mode and check the value. Hope this will help you.
case('3'):
{
cout<<"Value of userInput is: "<<userInput<<endl;
cout << getTitle(movieTitle);
break;
}
Alternately you can add the below line of code just before cin like below
std::cin.clear();
cin >> userInput;
I recommend inputting an integer instead of a character for your input.
You will need to change the case values too:
int selection = 0;
//...
cin >> selection;
switch (selection)
{
case 1:
//...
}
You won't have to worry about characters in the buffer. The stream will fail if an integer is not read.
I am calling the function below by a character 'a', I want to call another function by char 'b' to make a file after displayEntry(i); I am confused to create a file from display fun(), can anyone please help me out ?
In my assignment it is written as below :
(a) Search a certain last name
(b) Save the search result in a file
Where (a) is done but got stuck with (b)...........
// My code is :
void addBook::searchEntry() {
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i) {
if(strcmp(lastname, entries[i].lastName) == 0) {
cout << "Found ";
displayEntry(i);
}
cout<<endl;
}
}
use fstream to write and read from/to files:
#include <fstream> // add this to your inclusion
// My code is :
void addBook::searchEntry()
{
ofstream out("example.txt", ios::out);
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0; i < count; ++i)
{
if(strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Found ";
displayEntry(i);
out << lastname << endl;
}
cout<<endl;
}
out.close(); // don't forget to close files after you're done with using them
}
I have written this code and I am supposed to read in a txt file and read every other line in the txt file to the string array bookTitle[ARRAY_SIZE] and the other every other line to bookAuthor[ARRAY_SIZE]. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ARRAY_SIZE = 1000;
string bookTitle [ARRAY_SIZE];
string bookAuthor [ARRAY_SIZE];
int loadData(string pathname);
void showAll(int count);
//int showBooksByAuthor (int count, string name);
//int showBooksByTitle (int count, string title);
int main ()
{
int number, numOfBooks;
char reply;
string bookTitles, authorName, backupFile;
cout << "Welcome to Brigham's library database." << endl;
cout << "Please enter the name of the backup file:";
cin >> backupFile;
numOfBooks = loadData (backupFile);
if (numOfBooks == -1) {
cout << endl;
} else {
cout << numOfBooks << " books loaded successfully." << endl;
}
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All:";
cin >> reply;
do {
switch (reply) {
case 'a':
case 'A':
cout << "Author's name: ";
cin >> authorName;
showBooksByAuthor (numOfBooks, authorName);
cout << endl;
break;
case 'q':
case 'Q':
cout << endl;
break;
case 's':
case 'S':
showAll(numOfBooks);
break;
case 't':
case 'T':
cout << "Book title: ";
cin >> bookTitles;
showBooksByTitle(numOfBooks, bookTitles);
cout << endl;
break;
default:
cout << "Invalid input" << endl;
break;
}
} while (reply != 'q' && reply != 'Q');
while (1==1) {
cin >> number;
cout << bookTitle[number] << endl;
cout << bookAuthor[number] << endl;
}
}
int loadData (string pathname){
int count = 0, noCount = -1;
ifstream inputFile;
string firstLine, secondLine;
inputFile.open(pathname.c_str());
if (!inputFile.is_open()) { //If the file does not open then print error message
cout << "Unable to open input file." << endl;
return noCount;
}
for (int i = 0; i <= ARRAY_SIZE; i++) {
while (!inputFile.eof()) {
getline(inputFile, firstLine);
bookTitle[i] = firstLine;
getline(inputFile, secondLine);
bookAuthor[i] = secondLine;
cout << bookTitle[i] << endl;
cout << bookAuthor[i] << endl;
count++;
}
}
return count;
}
void showAll (int count) {
for (int j = 0; j <= count; j++) {
cout << bookTitle[j] << endl;
cout << bookAuthor[j] << endl;
}
}
So I have the loadData function which I am pretty sure is my problem. When I have it print out each string[ith position] while running the loadData function it prints out each title and author just as it appears in the txt file. But then when I run the void showAll function which is supposed to be able to print the entire txt doc to the screen it doesn't work. Also just I checked to see if the strings were actually stored in memory and they were not. (After my do while loop I have a while loop that accepts input of type int and then prints the string array of the [input position]. This prints nothing. So what do I have to do to actually store each line to a different position in the string array(s)? Feel free to correct my code but it isn't pretty yet considering I still have two functions that I haven't done anything too. (Commented out).
You main problem is that you try to read you data using two loops rather than just one! You want read until either input fails or the array is filled, i.e., something like this:
for (int i = 0;
i < ARRAY_SIZE
&& std::getline(inputFile, bookTitle[i])
&& std::getline(inputFile, bookAuthor[i]); ++i) {
}
The problem with the original code is that it never changes the index i and always stores values into the cell with index 0. Since the input isn't checked after it is being read, the last loop iteration fails to read something and overwrites any earlier stored value with an empty value. Once reading of the stream fails the outer loop iterates over all indices but doesn't do anything as the check to the inner loop is always false.
We did a very similar type of code in C++ class but my version isn't working right, even though it is line-by-line (almost) the same.
My code is meant to save a user's Pokemon and they can add and delete as they please. My display function is working but my add and delete function are not. All the files are opening, but it's not overwriting the file like it's supposed to. Really unsure of what to do, I'm very much a beginner and I don't know much.
Here is what I've got so far:
string name[100];
string type[100];
int level[100];
string newPokemon;
string newType;
int newLevel;
ifstream fin;
ofstream fout;
int numberOfPokemon = 0;
//Input Pokemon Info
cout << "Name of Pokemon: ";
getline(cin, newPokemon);
cin.ignore(100, '\n');
cout << "Pokemon type: ";
getline(cin, newType);
cin.ignore(100, '\n');
cout << "Pokemon level: "; //weird gap between "Pokemon type" and "pokemon level". I have to press enter twice from "pokemon type" to get to "pokemon level"
cin >> newLevel;
cin.ignore(5, '\n');
fin.open("pokemon.txt");
//Put file in array
if (fin.is_open())
{
while (isalnum(fin.peek()) && numberOfPokemon < 100)
{
getline(fin, name[numberOfPokemon]);
getline(fin, type[numberOfPokemon]);
fin >> level[numberOfPokemon];
fin.ignore(100, '\n');
if (name[numberOfPokemon] != newPokemon)
numberOfPokemon++;
}
fin.close();
}
//Output file
fout.open("pokemon.txt");
if (fout.is_open())
{
for (int i = 0; i < numberOfPokemon; i++)
{
fout << name[i] << "\n";
fout << type[i] << "\n";
fout << level[i] << "\n";
}
//Tack on new piece
fout << newPokemon << "\n";
fout << newType << "\n";
fout << newLevel << "\n";
fout.close();
cout << "Add Successful\n";
}
else
{
cout << "Add Failure\n";
}
and now my delete function:
string name[100];
string type[100];
int level[100];
int pokemonCount = 0;
string deletedPokemon = "";
bool found = false;
ifstream fin;
cout << "Which Pokemon would you like to delete?" << endl;
getline(cin, deletedPokemon);
cin.ignore(5, '\n');
fin.open("pokemon.txt");
if (fin.is_open())
{
while (isalnum(fin.peek()))
{
getline(fin, name[pokemonCount]);
getline(fin, type[pokemonCount]);
fin >> level[pokemonCount];
fin.clear();
fin.ignore(100, '\n');
if (deletedPokemon == name[pokemonCount])
{
pokemonCount--;
found = true;
}
pokemonCount++;
}
fin.close();
cout << "ya the file opened" << endl; //always appears
}
ofstream fout;
fout.open("pokemon.txt");
if (fout.is_open())
{
for (int i = 0; i < pokemonCount; i++)
{
fout << name[i] << "\n";
fout << type[i] << "\n";
fout << level[i] << endl;
}
fout.close();
cout << "pokemon removed\n";
cout << "the file opened."; //it is returning that the file opened in both occasions in this function but nothing is happening!
}
else
{
cout << "removal failure";
cout << "The file didn't open";
}
return found;
at the end of this function (if I chose to delete one), it will offer the "Would you like to add a Pokemon?" but it wont let me input an answer and it will just end the program.
The default behaviour of ofstream::open is to simply open the file for reading and writing. If you want to overwrite the file, you need to specify it in your call to open.
fout.open("pokemon.txt", ios_base::in|ios_base::out|ios_base::trunc);
Make sure your file is not marked as read-only under properties.
Also, there is a bug in your delete function:
The bfound should be replace with nDelete pokemon and when you write out the file:
if (deletedPokemon == name[pokemonCount])
{
pokemonCount--;
found = true;
nDeleteIndex = i;
}
....
for (int i = 0; i < pokemonCount; i++)
{
if(i == nDeleteIndex)
continue;
fout << name[i] << "\n";
fout << type[i] << "\n";
fout << level[i] << endl;
}
Right now it will re-write all your pokemons without skipping the one you want to delete!
Also, what happens if the user has 155 pokemons for a full index. You want to use:
std::vector<string> names;
....
string szPokemon;
getline(fin, name[numberOfPokemon]);
names.push_back(szPokemon);
Thus you no longer have a limit !
Here is much cleaner code, its much more maintainable and whenever you add/remove a field from the pokemon (Shiny? Male/Female ? Unique ?) you will be able to easily do it inside the CPokemonObject instead of having to copy paste the code 100 times.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
#define POKEMON_FILE "Pokemon.txt"
class CPokemon
{
public:
string szName;
string szType;
int nLevel;
CPokemon() : szName("Pika"), nLevel(10), szType("Lightning")
{};
void Read(ifstream &file)
{
file >> szName;
file >> szType;
file >> nLevel;
};
void Write(ofstream &file)
{
file << szName << endl;
file << szType << endl;
file << nLevel << endl;
};
void CreatePokemon()
{
//Input Pokemon Info
cout << "Name of Pokemon: ";
getline(cin, szName);
cout << "Pokemon type: ";
getline(cin, szType);
cout << "Pokemon level: "; //weird gap between "Pokemon type" and "pokemon level". I have to press enter twice from "pokemon type" to get to "pokemon level"
cin >> nLevel;
}
};
void WritePokemons(vector<CPokemon>& Pokemons)
{
ofstream fout;
fout.open(POKEMON_FILE);
//check the file open
if (!fout.is_open())
{
cout << "removal failure";
cout << "The file didn't open";
return;
}
//Write out all the pokemons
for (unsigned int i = 0; i < Pokemons.size(); i++)
Pokemons[i].Write(fout);
fout.close();
}
void ReadPokemons(vector<CPokemon>& Pokemons)
{
ifstream fin;
fin.open(POKEMON_FILE);
if (fin.is_open())
{
while (isalnum(fin.peek()))
{
CPokemon Pokemon;
Pokemon.Read(fin);
Pokemons.push_back(Pokemon);
}
fin.close();
cout << "ya the file opened" << endl; //always appears
}
}
bool DeletePokemon()
{
vector<CPokemon> Pokemons;
string szPokemonToDelete = "";
cout << "Which Pokemon would you like to delete?" << endl;
cin >> szPokemonToDelete;
//Read all pokemons
ReadPokemons(Pokemons);
ofstream fout;
fout.open("pokemon.txt");
//check the file open
if (!fout.is_open())
{
cout << "removal failure";
cout << "The file didn't open";
return false;
}
bool bFound = false;
for (unsigned int i = 0; i < Pokemons.size(); i++)
{
//Skip the pokemon to delete
if(Pokemons[i].szName == szPokemonToDelete)
{
bFound = true; //we found the pokemon to delete
continue;
}
Pokemons[i].Write(fout);
}
fout.close();
return bFound;
}
void AddPokemon()
{
vector<CPokemon> Pokemons;
//Read all pokemons from the file
ReadPokemons(Pokemons);
//Create the new porkemon
CPokemon Pokemon;
Pokemon.CreatePokemon();
//Add the pokemon to the list
Pokemons.push_back(Pokemon);
//Output file
WritePokemons(Pokemons);
}