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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm a kind of beginner in C++ and need little help here.
How can I create a C++ program which takes two integers from the user and It displays the sequence in this format using Nested Loops:
Enter the starting integer: 11
Enter the ending integer: 18
(11,11)(11,12)(11,13)(11,14)(11,15)(11,16)(11,17)(11,18)
(12,12)(12,13)(12,14)(12,15)(12,16)(12,17)
(13,13)(13,14)(13,15)(13,16)
(14,14)(14,15)
or
Enter the starting integer: 1
Enter the ending integer: 5
(1,1)(1,2)(1,3)(1,4)(1,5)
(2,2)(2,3)(2,4)
(3,3)
I wrote the code something like this before:
int startingval;
cout << "Enter starting integer: ";
cin >> startingval;
int endingval;
cout << "Enter Ending integer: ";
cin >> endingval;
int looptime;
looptime = endingval;
endingval = startingval;
for (int i = 0; i < startingval; i++)
{
cout << "(" << startingval << ", " << endingval << ")";
endingval++;
if (endingval == looptime + 1)
{
i = startingval;
}
}
return 0;
But, This is not what I need. Please Help me :)
first, you can't use any tags except that's in your question.
the only difference between the sequence you want and the normal nested loop between all elements in the array is the ending point is decreesing
I suggest you try the following code:
int start;
cout << "Enter starting integer: ";
cin >> start;
int end;
cout << "Enter Ending integer: ";
cin >> end;
for(int i=start;i<=end;i++){
for(int j=i;j<=end;j++)
cout << "(" << i << ", " << j << ")";
cout<<endl;
end--;
}
I hope be useful, Let me know if there is a problem.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
For practice, I'm writing a program that takes in data from the user about the classes they took and at the end, outputs that data into a file of a neat looking transcript with a bunch of calculations such as GPA, total units, etc.
I'm using a do-while loop but it doesn't seem to be working.
I believe the problem is with the addClass variable, as even though I specified it to only ask for another class if addClass = 1, it still asks for one when I input 0. Does anyone who has more experience have a solution to this? Thank you.
//Prog: Unofficial Transcript Creator
//Modified 5-08-2018
#include<iostream>
#include<iomanip>
#include<cmath>
#include<fstream>
#include<string>
using namespace std;
int main() {
//Declares.
string classSubject;
int classCode;
string professorFirst, professorLast;
int classUnits;
string grade;
int addClass;
ofstream fout;
//Open the output file.
fout.open("UNOFFICIAL_TRANSCRIPT.TXT");
//Test if the file opened.
if (fout) {
cout << "The output file has been located. Please begin input of transcript data." << endl;
cout << endl;
}
else
cout << "ERROR ID107: The output file was not found. Please create a blank text document named UNOFFICIAL_TRANSCRIPT.TXT.";
//Prompt user for information.
do {
addClass = 0;
cout << "Please enter the class subject: ";
cin >> classSubject;
cout << endl;
cout << "Please enter the class code: ";
cin >> classCode;
cout << endl;
cout << "Please enter the first name of the professor: ";
cin >> professorFirst;
cout << endl;
cout << "Please enter the last name of the professor: ";
cin >> professorLast;
cout << endl;
cout << "How many units is the class worth? ";
cin >> classUnits;
cout << endl;
cout << "What grade did you get in the class? ";
cin >> grade;
cout << endl;
cout << "Would you like to add another class? Type 1 for yes or 0 for no. ";
cin >> addClass;
cout << endl;
fout << setw(12) << classSubject << classCode;
}
while
(addClass = 1);
system("pause");
return 0;
}
Replace while(addClass = 1 ) with while(addClass == 1).
The former will assign the value 1 to addClass and then check whether the value of the expression (which is the value assigned, i.e. 1) is non-zero.
Since this value is non-zero, your loop would never be able to get out of your loop.
The latter performs an equality check to see if the value of addClass is equal to 1.
IMHO, while (addClass = 1) should also raise a warning on any decent compiler( especially if all warnings are enabled ), as it is a very common mistake/typo.
Also, if it was not a typo, then now would be a good time to brush up your C++ basics.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making a game and I want it to only run if player consents by saying PLAY but it won't run. Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int balance = 500;
char start;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(start == 'PLAY') {
cout << "Your beginning numbers are!" << endl;
}
}
A char is a single character, like 'P'. If you expect the user to enter a full string, you want to use std::string. Additionally, you probably want to simply check if the user entered the string you wanted - not while - unless you want to prompt again at the end of your game.
Corrected code would be:
std::string start;
// ...
std::cin >> start;
if (start == "PLAY") {
// play the game
}
start is a char and not an array of char. You are only storing one letter in start
Change that, and also change 'PLAY' to "PLAY". Consider using a std::string instead.
Example of what you can do:
int balance = 500;
char start[256];
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (!strcmp(start, "PLAY")) { // #include <cstring>
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
Or with using std::string:
int balance = 500;
string start;
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (start == "PLAY") {
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
change char start; to char start[100];
and while(start == 'PLAY') to while(start == 'PLAY')
Here is the final code
int balance = 500;
char start[100];
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! "<< endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(!strcmp(start,"PLAY")) {
cout << "Your beginning numbers are!" << endl;
}
You are trying to take in as input a string, but storing using a character.
use
char start[SIZE];
Also are u sure comparing with 'PLAY' is being done in the right way? Use " for strings. Better to use string functions.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hey guys I've got this piece of code, posted below. I've added the while loop to make sure that only numeric input is used, but when I use it, it requires me to input the number twice, or press enter and then input the number.
Output would be:
Input number : 1
1
then it would it would print the results. How can I fix this Cheers.
void Dictionary::SearchNumeric()
{
int x;
cout << "Input number : ";
while (!(cin >> x))
{
cout << "Invalid input. Try again: ";
cin.ignore(numeric_limits<streamsize>::max());
}
string searchWord = myWords[x]->word;
cout << "Word searched: " << searchWord << endl;
cout << "Definition: \n" << myWords[x]->definition << endl;
cout << "Type: " << myWords[x]->type << endl;
int wordIndex = 0;
//while (myWords[wordIndex]->word.compare(x) != 0) {
//needs to return scrabble score
wordIndex++;
//break;
//}
}
Get rid of the first cin >> x;, set the string searchWord after the while
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.