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.
Related
I am new to programming and I can't seem to figure out how to fix this problem. My assignment is very simple, to order two words alphabetically using only the strcmp function.
My program compiles and runs, but it doesn't progress until I fully fill the array with characters, but we are meant to be able to use words of different lengths.
Here is what I have written:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int x;
char wordone[10] , wordtwo[10];
cout << "Please enter your first word: \n";
for(x=0; x<10; x++) cin >> wordone[10];
cout << "Please enter the second word: \n";
for(x=0; x<10; x++) cin >> wordtwo[10];
if(strcmp(wordone, wordtwo)<0)
{
cout << wordone << endl << wordtwo;
}
if ( strcmp( wordone,wordtwo)>0)
{
cout << wordtwo << endl << wordone;
}
else
{
cout << wordone << endl << wordtwo;
}
return 0;
}
And the output looks like this:
Please enter your first word:
help
me
please
Please enter the second word:
hello
how
`
#
àu0þ
I've been trying every combination I can think of, any help would be much appreciated!
For input. Use getline or directly take input.
Instead of this -
cout << "Please enter your first word: \n";
for(x=0; x<10; x++) cin >> wordone[10];
Possible solutions.
Do this -
char name[10];
cin>>name;
or do this
string s;
cin>>s; // simply take input like ordinary variable. Rember to #include<string>
or do this --
string s; // for getline this is must. Use string
getline(cin,s);
This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 3 years ago.
so I'm working on a homework problem for my CS175 C++ course. We have a homework assignment where we have to make a shorting hat, kinda like what's in Harry Potter. I've got 99% of the code down, however the thing that is tripping me up is how to read in a string with white space.
We need to be able to input full names so obviously just using std::cin >> won't work. The problem is that I can't seem to get any of the methods to work that I've tried so far.
This is my code:
#include <iostream>
#include <string>
int main()
{
int NumStudents;
std::string NameStudents;
int StartValue;
int House;
std::string HouseName;
int NumCornfolk = 0;
int NumEsophagus = 0;
int NumBob = 0;
//How many students are there?
std::cout << "How many students are there? \n";
std::cin >> NumStudents;
for (StartValue = 0; StartValue < NumStudents; StartValue++) {
std::cout << "Please enter the name of the next student. \n";
std::cin >> NameStudents; \\**THE PROBLEM IS HERE**
//Assings the House
House = rand() % 100 + 1;
if (House <= 19) {
HouseName = "Cornfolk! \n";
NumCornfolk++;
}
else if (House > 19 && House < 50) {
HouseName = "Esophagus! \n";
NumEsophagus++;
}
else if (House >= 50) {
HouseName = "Bob! \n";
NumBob++;
}
std::cout << NameStudents << " got " << HouseName << std::endl;
}
//Prints Results
std::cout << "Number of Students in each House: \n";
std::cout << "Cornfolk:" << NumCornfolk << " Esophagus:" << NumEsophagus << " Bob:" << NumBob;
}
The line of code that reads std::cin >> NameStudents; is what's causing the problem. I've seen methods that say to use something along the lines of "std::cin.getline (name,256);" but cin.getline throws an error at the period and won't compile.
Being able to read in the names correctly is only 2/11 points, so it's not that big of a deal, but I would like to know why the suggested methods are not working here.
Thank you. This question is different from ones asked before mods.
Use std::getline, like this:
std::getline(std::cin, NameStudents);
Here's an example from https://en.cppreference.com/w/cpp/string/basic_string/getline:
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
So below is my while loop code. Loop is endless when I enter anything other than double for cin. How do I make it so that "cout << " Invalid! Please enter the correct amount. " only comes once and that it asks for cin straight after that.?
int main ()
double pWeekdays7am_7pm;
cout << "\n Please enter the amount of electricity (kWh) produced in the following time periods. If no electricity was produced, enter \"0\"" << endl << endl;
cout << " Monday-Friday (7am-7pm) ";
cin >> pWeekdays7am_7pm;
while (pWeekdays7am_7pm < 0)
{ cout << " Invalid! Please enter the correct amount. " ;
cin >> pWeekdays7am_7pm;
cout << "Enter positive number, or 0\n";
cin >> pWeekdays7am_7pm;
if (pWeekdays7am_7pm < 0)
{
cout << " Invalid! Please enter the correct amount. ";
while (pWeekdays7am_7pm < 0)
{
cin.sync(); cin.clear(); // get rid of anything unwanted
cin >> pWeekdays7am_7pm;
}
}
Assuming you still have the problem a solution to the problem you have would be the following:
#include <limits> // require for limits
#include <iostream> // required for I/O functionality
using namespace std; // to avoid using std:: all the time.
int main (int argc, char **argv) {
double pWeekdays7am_7pm;
cout << "\n Please enter the amount of electricity (kWh) produced " <<
"in the following time periods. If no electricity was " <<
"produced, enter \"0\"" << endl << endl;
cout << "\tMonday-Friday (7am-7pm) ";
cin >> pWeekdays7am_7pm;
/*
condition to advance, we check for two things
1) if the conversion to *double* failed, hence cin.fail will return *true*
2) if the converted value is within our limits (>= 0)
*/
while (cin.fail() || pWeekdays7am_7pm < 0) {
cout << "\tInvalid value! Please enter the correct amount: " ;
/* reset the stream state */
cin.clear();
/* truncate existing contents up to new line character */
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
cin >> pWeekdays7am_7pm;
}
/* finally return */
return 0;
}
The comments should be pretty straight forward to explain what this code does but should you have any more questions update here and I'll try to answer. I would suggest picking some online resources or a good C++ book and read it.
Hope this helped.
I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}
You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}
Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?