Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
When I run my program it works the first time, the correct input is read and output is written to my output file but once I run it a second time it doesn't write anything the file is just blank even though it reads everything correctly. I can't seem to understand where its messing up or how and I really want to know. The two images are my first and second runs just that after the second run my output file is blank.
first run
second run
#include<iostream>
#include<iostream>
#include<cstdlib>
#include<time.h>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int i=0;
int number; // The correct number
int guess=0; // The user's guess
int numGuesses=0; // The number of times the user has guessed
string lines;
string player;
ifstream ifile;
ofstream ofile;
//ofstream myfile;
//
string names[10];
int scores[10];
ifile.open("high_score.txt");
string first_last_name;
string temp;
int score;
int index=0;
string title;
bool topten=false;
cout <<"Welcome to the number guessing game. The top 10 best scores so far are: "<<endl;
while(!ifile.eof())
{
//getline(ifile,lines);
ifile >>first_last_name;
//cout << first_last_name;
ifile >> temp;
first_last_name.append(" ");
first_last_name.append(temp);
ifile >> score;
names[index]=first_last_name;
scores[index++]=score;
}
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
for (int i=0; i < 10; i++)
{
cout << names[i] << " " << scores[i] <<endl;
}
// Seed the random generator.
srand(static_cast<int> (time(NULL)));
// Generate a random number between 1 and 100.
number = (rand() % 100) + 1;
cout << "Let's play the number guessing game! What is your name? " <<endl;
getline(cin,player);
cout << endl;
while(guess!=number)
{
cout << "guess the number the computer randomly picked between 1 - 100: ";
cin >> guess;
numGuesses++;
// Check if the user has guessed the correct number.
// If not, tell him if his guess is too low or too high
if(number > guess)
{
cout << "sorry, your guess is too low" << endl;
}
else if(number < guess)
{
cout << "sorry, your guess is too high" << endl;
}
else
{
cout << "You guessed right!!!!"<<endl;
cout << "You win!!!" << endl;
break;
}
}
cout << "It took you "<< numGuesses << " guesses "<< player<< endl;
////////////////////////////////////////////////////////////////////////
if (numGuesses<4)
{
cout << "Amazing! Or was it luck" << endl;
}
else if(numGuesses<6)
{
cout <<"That's a very good score..." <<endl;
}
else if (numGuesses<8)
{
cout << "That's pretty good but you can do better..." << endl;
}
else if ( numGuesses<10)
{
cout << "Not too shabby, but not too good either..."<< endl;
}
else
{
cout << "What a terrible score!..." << endl;
}
for(int i=0; i < 10; i++)
{
if(numGuesses <= scores[i])
{
for( int k=9;k>i;k--)
{
scores[k]=scores[k-1];
names[k]=names[k-1];
}
scores[i]=numGuesses;
names[i]=player;
topten=true;
break;
}
}
if(topten==true)
{
cout << "Hey, you made it to the top ten , Congratzzzzzzzz!!!!" <<endl;
}
ofile.open("high_score.txt");
for(int i=0;i<10;i++)
{
ofile <<"\t"<< names[i] << " " << scores[i] <<endl;
ofile << endl;
}
return 0;
}
You need to close the input file before you open the output file, since they are both referring to the same file.
The closing can be done explicitly by calling ifile.close() or implicitly by making ifile go out of scope before you open the output file.
The latter can be done like this:
{
ifstream ifile;
ifile.open("high_score.txt");
// do stuff with ifile
}
ofstream ofile;
ofile.open("high_score.txt");
// do stuff with ofile
Where is ifile.close() and ofile.close()
you should close else your stream will go into invalid state.
Related
I'm trying to make a program that prints all the numbers from 100-999. After that you get to choose how many numbers you want to find. Then you type the number's position and it will be outputed.
There is one problem. The string, named str, stops storing at the number 954.
Here's the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//Prints to myFile the numbers from 100 to 999 without a space in between. Like this: 100101102...999
ofstream myFile("numere.txt");
for(int i = 100; i <= 999; i++)
myFile << i;
//Makes the string str to store the line: 100101102103...999. But only stores until 954 (100101102..954)
ifstream myFileRead("numere.txt");
string str;
while(getline(myFileRead, str))
cout << str << endl;
//Ouputs the lenght that should be 2700 but is instead 2565
cout << endl;
cout << "String legth: " << str.size() << endl;
cout << endl;
int n, k;
cout << "Enter how many numbers do you want to find: ";
cin >> n;
for(int i = 1; i <= n; i++){
cout << "Enter number position(it starts from 0) : ";
cin >> k;
cout << "Here's the number on position " << k << ": " << str.at(k);
cout << endl;
}
system("pause>0");
}
Thanks for your attention. I’m looking forward to your reply.
C++ streams are buffered. When you use << to write to a file it is not immediately written to the file.
Try to close or flush the ofstream before you read from it:
myFile.close(); // or...
myFile.flush();
For more details I refer you to flush() and close().
PS: Actually it is rather rare that you need to close a fstream explicitly. You wouldn't need to do it when you used seperate functions for writing and reading:
void write_to_file() {
std::ofstream myFile("numere.txt");
//...
}
void read_from_file() {
std::istream myFile("numere.txt");
//...
}
Because the destructor of ofstream already closes the file.
I have decided to make an anagram solver for my dad. I am quite new to programming, but i figured I can still make it. My finished product works, but it is really slow, for instance it took about 15+ mins to find all combinations of 8 characters. I am looking for ways to optimize it / make it faster.
Working with MinGW c++ compier, on Clion 2019.3.4, cpu: i7 9700k, and RAM: 16GB/3200mhz.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
//Menu for interacting with user, not really important
void menu() {
cout << "=========================" << endl;
cout << "======== !WOW! ==========" << endl;
cout << "=========================" << endl;
cout << "1 ... INSERT" << endl;
cout << "2 ... PRINT" << endl;
cout << "3 ... LIMIT WORD LENTGH" << endl;
cout << "4 ... NEW GAME" << endl;
cout << "0 ... EXIT" << endl;
cout << "=========================" << endl;
cout << "Select: ";
}
//Function to find all possible combinations from letters of a given string
void get(vector<string> &vec, string str, string res) {
vec.push_back(res);
for (int i = 0; i < str.length(); i++)
get(vec, string(str).erase(i, 1), res + str[i]);
}
//Only for testing purposes
void printVec(vector<string> vec) {
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
}
//Function to check if a given word exists in given .txt file
bool checkWord(vector<string> &vec2, string filename, string search) {
string line;
ifstream myFile;
myFile.open(filename);
if (myFile.is_open()) {
while (!myFile.eof()) {
getline(myFile, line);
if (line == search) {
vec2.push_back(line);
return true;
}
}
myFile.close();
} else
cout << "Unable to open this file." << endl;
return false;
}
int main() {
int selection;
bool running = true;
string stringOfChars;
vector<string> vec;
vector<string> vec2;
do {
menu();
cin >> selection;
switch (selection) {
case 1:
cout << "Insert letters one after another: ";
cin >> stringOfChars;
get(vec, stringOfChars, ""); //fill first vector(vec) with all possible combinations.
break;
case 2:
for (int i = 0; i < vec.size(); i++) {
if (checkWord(vec2, "C:/file.txt", vec[i])) { //For each word in vector(vec) check if exists in file.txt, if it does, send it in vector(vec2) and return true
//Reason for vec2's existence is that later I want to implement functions to manipulate with possible solutions (like remove words i have already guessed, or as shown in case 3, to limit the word length)
cout << vec[i] << endl; //If return value == true cout the word
}
}
break;
case 3:
int numOfLetters;
cout << "Word has a known number of letters: ";
cin >> numOfLetters;
for (int i = 0; i < vec2.size(); i++) { /*vec2 is now filled with all the answers, we can limit the output if we know the length of the word */
if (vec2[i].length() == numOfLetters) {
cout << vec2[i] << endl;
}
}
break;
case 4:
vec.clear();
vec2.clear();
break;
case 0:
running = false;
break;
default:
cout << "Wrong selection!" << endl;
break;
}
cout << endl;
} while (running);
return 0;
}
file.txt is filled with all words in my language, It's alphabetically ordered and it's 50mb in size.
aachecnska
aachenskega
aachenskem
aachenski
.
.
.
bab
baba
babah
.
.
.
Any recommendations or off topic tips would be helpful. One of my ideas is to maybe separate file.txt in smaller files, like for example putting lines that have same starting letter in their own file, so A.txt would only contain words that start with A etc... And than change the code accordingly.
this is where you need to use a profiler. on Linux, my favorite is kcachgrind
http://kcachegrind.sourceforge.net/html/Home.html
it gives you line-by-line timing information and tells you which part of the code you should optimize the most.
of course, there are many profilers available, including commercial ones.
I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I get the error:
'_sleep': This function or variable has been superceded by newer
library or operating system functionality. Consider using Sleep
instead. See online help for details.
Can you guys and/or girls tell me what library is causing this error?
Code:
// A program to keep track of points and time and to give a random letter for the game scattergories
#include<iostream>
#include<ctime>
#include<string>
using std::cout;
using std::cin;
using std::string;
using std::getline;
void ltr() //gives a random letter
{
srand(time(NULL)); //gives a differant pattern every time
char letter;
letter = rand() % 27 + 64; //assigns a random letter in ascii code to a char (resulting in a random letter)
cout << "The letter is " << letter << "\n";
}
void timer()
{
cout << "You got 1.5 minutes to finish\n";
for (int i = 90; i > 0; i--)
{
if (i % 5 == 0)
cout << i << "\n";
_sleep(1000);
}
cout << "DING DONG!!! DING DONG!!! Time's up!!!\n";
}
void table()
{
int plr, ctr;
string lst[5][20]; //first dimantion: how many players. second dimantion: how many catagories, third dimantion(if added) will be the round
cin >> plr >> ctr; //parameters for later
cin.ignore(); //To avoid the "getline" reading the last input
for (int x = 0; x<plr; x++) //the player changes only after the previus player finishes
{
timer();
for (int i = 0; i<ctr; i++) //changing catagory
{
getline(cin, lst[x][i]);
}
system("cls");
cout << "Next player\n";
}
for (int x = 0; x<plr; x++) //this part (the whole "for" loop) is for confirming
{
cout << "Player number " << x + 1 << ": ";
for (int i = 0; i<ctr; i++)
{
cout << lst[x][i] << " ";
}
cout << "\n";
}
_sleep(5000);
}
int points() //points per round
{
int a, b, c, sum;
cout << "How many sections only you got?\n"; //worth 15 points
cin >> a;
cout << "How many words only you got?\n"; //worth 10 points
cin >> b;
cout << "How many words you and another person got?\n"; //worth 5 points
cin >> c;
sum = a * 15 + b * 10 + c * 5;
return sum; //Note: It doesn't matter how many sections there are.
}
int act()
{
int Points;
ltr();
table();
Points = points();
cout << "You have earned " << Points << " this round\n\n";
return Points;
}
int main()
{
int Points;
cout << "Starting in five seconds\n";
_sleep(5000);
Points = act();
for (;;) //inf loop
{
int ph;
cout << "Press 1 to continue or anything else to stop\n";
cin >> ph;
if (ph == 1)
{
Points += act();
}
else
{
break;
}
}
cout << "You have earned a total of " << Points << " great job!";
_sleep(5000); //time to read the last text
return 0;
}
/* To do list:
*Convert to arduino
*Make timer work in background of of table
*Check if words in the table (for differant players) are the same and give points accordingly
*Check if words are actual words (connect an online dictonary?)
*Make interface? (if possible and I have time to learn how)
*Think of what to do with Hardwear
*Comment rest of the code
*/
For using Sleep() function you need
#include <windows.h>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
So I have been making this program for a while now. I have looked all over the internet and none of the solutions I have found work. Every time I put in my input in the arr[i].question and arr[i].answer, it says that my question is wrong without me giving a answer to the question. I have tried using cin.ignore(), cin.clear(), and cin.sync(). I might have been using them in the wrong places but i'm not sure. I might be confusing, so just look at the code.
Here is the input format.
cin >> count;
cin.ignore();
for(int i =0; i < count; i++){
cout << "Enter the question.\n" << endl;
//enter the question
getline(cin, arr[i].question);
cin.ignore();
cout << "Enter the answer.\n" << endl;
//enter the answer
getline (cin, arr[i].answer);
cin.ignore();
}
and here is the out put format to quiz you.
for(int j =0; j < count; j++){
cout << "\n" << arr[j].question << endl;
getline(cin, userguess);
if(arr[j].answer.compare(userguess) !=0){
cout << "Wrong. Keep trying!\n";
incorrect++;
total++;
}
if(arr[j].answer.compare(userguess) ==0){
cout << "Nice job. Keep it up!\n";
correct++;
total++;
}
Whenever I put in my question it doesn't output a question in the console or let me put in an answer. It just says wrong.
A little help please?
edit: here is the whole code:
// final PROJECT.cpp : Defines the entry point for the console application.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include <cstdio>
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <cstdlib>
using namespace std;
struct flashcards{
string question;
string answer;
}FC1, FC2, FC3, FC4, FC5, FC6, FC7, FC8, FC9, FC10, FC11, FC12, FC13, FC14, FC15, FC16, FC17, FC18, FC19, FC20;
int _tmain(int argc, _TCHAR* argv[])
{
system ("color 4B");
string userguess;
string again;
flashcards arr[10000];
int count;
float correct=0;
float incorrect=0;
float total=0;
//one major problem, wont accept spaces.
cout<< "Flash Card Runner\n";
cout<< "This program was made by Jacob Malcy\n";
cout<< "Beta 3.8\n";
cout<< "IN ORDER FOR YOU TO HAVE MULTIPLE WORD FLASH CARDS,\n";
cout << "SKIP NUMBER ONE FLASHCARD QUESTION AND ANSWER!\n";
cout<< "This bug is currently being worked on.\n";
cout << "If you happen to have problems conntact Jacob.\n";
int choice;
cout<< "Would you like to create or test? Enter 0 for create and 1 for test.\n";
cin >> choice;
if(choice==0){
//Creating new deck of cards
cout<< "How many flashcards do you want?\n";
cin >> count;
cin.clear();
for(int i =0; i < count; i++){
cout << "Enter the question.\n" << endl;
//enter the question
getline(cin, arr[i].question);
cin.ignore();
cout << "Enter the answer.\n" << endl;
//enter the answer
getline (cin, arr[i].answer);
cin.ignore();
}
}
else if(choice==1){
//Reading in new file
cout << "Reading file...\n";
string line;
ifstream myfile ("Save.txt");
if (myfile.is_open())
{
count = 0;
while ( myfile.good () )
{
getline (myfile,line);
arr[count].question = line;
cout << line << endl;
getline (myfile,line);
arr[count].answer = line;
cout << line << endl;
count++;
}
myfile.close();
}
else cout << "Unable to open the file";
}
do
{
for(int j =0; j < count; j++){
cout << "\n" << arr[j].question << endl;
getline(cin, userguess);
if(arr[j].answer.compare(userguess) !=0){
cout << "Wrong. Keep trying!\n";
incorrect++;
total++;
}
if(arr[j].answer.compare(userguess) ==0){
cout << "Nice job. Keep it up!\n";
correct++;
total++;
}
}
cout<< "The number of correct questions answered was: \n" << correct << endl;
cout<<"The number of total questions answered was: " << total <<"\n";
cout<< "The number of incorrect questions answered was: \n" << incorrect << endl;
//cout<< total;
float percent = (correct/total)*100;
cout<< "The total percent you got right is: \n" << percent << "% correct" << endl;
system("pause");
cout << "Would you like to run the quiz again?\n"
<< "Type y or Y to run this again. If not, enter any other letter.\n";
cin >> again;
if((again == "y") || (again == "Y")){
correct=0;
incorrect=0;
total=0;
}
}while((again == "y") || (again == "Y"));
ofstream myfile ("Save.txt");
if (myfile.is_open())
{
for(int i =0; i <count; i++){
myfile << arr[i].question << "\n";
myfile << arr[i].answer << "\n";
}
myfile.close();
}
else cout << "Unable to save file";
cout << "Your finished with the quiz. Goodbye!\n";
system("PAUSE");
return 0;
}
When I run it, it comes out like this
Flash Card Runner
This program was made by Jacob Malcy
Beta 3.8
IN ORDER FOR YOU TO HAVE MULTIPLE WORD FLASH CARDS,
SKIP NUMBER ONE FLASH CARD QUESTION AND ANSWER!
This is a bug is currently being worked on.
if you happen to have problems, conntact Jacob.
Would you like to create or test? Enter 0 for create and 1 for test.
If i enter zero:
How many flashcards do you want?
say I enter two 2
Enter the question.
Hi ho
Enter the answer.
Merry oh
enter the question.
fi fa
enter the answer.
fo fum
then it just skips to:
Wrong. Keep trying!
erry oh
Before wrong, it should display the first question, and give me the oppertunity to answer.
It just says wrong before i can. then it displays the answer with the first character missing. There you go.
I presume you're calling ignore right after getline to get rid of the trailing newline character.
Do not do that. std::getline already extracts the newline character from the stream (and discards it), so you're ignoring the first character of the next line.