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 8 years ago.
Improve this question
I am supposed to write a program, that will ask a user to input a number and then display all the perfect squares starting from 1 to the input number^2. I have written this program, but I was asked to put it in a nested loop. The problem is, I don't know how I could turn this into nested loop format. Does anyone have any ideas?
Here is my program so far:
int input;
int number = 1;
cout << "Enter a number: ";
cin >> input;
if(input > 1) {
cout << "The perfect squares are: ";
do {
cout << number*number;
number++;
input--;
if(input == 1) {
cout << " and "; }
else {cout << ", ";}
}while(input > 1);
cout << number*number << ".";
}
else if(input == 1) {
cout << "1";
}
else {
cout << "None.";
}
Why does it need to be a nested loop? This can be done using a simple for loop.
unsigned int input;
cout << "Enter a number: ";
cin >> input;
for (unsigned int i = 1; i <= input; ++i)
{
cout << i << " squared is " << i * i << endl;
}
Working demo
The while loop equivalent would be
unsigned int input;
cout << "Enter a number: ";
cin >> input;
unsigned int i = 1;
while(i <= input)
{
cout << i << " squared is " << i * i << endl;
++i;
}
Related
I am a first year cs major. Today in our lab we had to debug some code and make it work. Below is the result.
#include <iostream>
using namespace std;
int main() {
int x = 3, y;
char myanswer;
int val= 1;
int num;
y = x;
cout << "y is set to: " << y << endl;
bool again = true;
int ans;
while (again) {
cout << "Please input a number: ";
cin >> y;
if (x > y)
cout << "X is greater than Y\n";
else {
cout << "X is less than Y" << endl;
cout << "would you like to input another number?" << endl;
cin >> ans;
if (ans != 1)
break;
}
cout << "would you like to input another number ?" << endl;
cin >> ans;
if (ans != 1)
again = false;
}
for (x = 0; x < 10; x++)
cout << x << endl;
cout << "What number would you like to find the factorial for? " << endl;
cin >> num;
cout << num;
for (int x = num; x > 0; x--) {
val *= x;
}
cout << "Are you enjoying cs161? (y or n) " << endl;
cin >> myanswer;
if (myanswer == 'y')
cout << "Yay!" << endl;
else
cout << "I hope you will soon!" << endl;
return 0;
}
After the cout regarding factorials, the cin's don't work and the user ceases to be able to enter input. So far my lab ta's and friends haven't been able to find the issue. The code has been compiled and exected on both my school's engineering servers and my local computer. On both the error persists.
almost certainly this caused an overflow
for (int x = num; x > 0; x--) {
val *= x;
}
what did you enter for num?
When you have a statement as:
cout << "would you like to input another number?" << endl;
The first instinct for the user would be to type y or n as an answer. You can help the user by providing a hint.
cout << "would you like to input another number (1 for yes, 0 for no)?" << endl;
If you do that, it would be better to be consistent throughout your program. The next prompt that seeks a y/n response must use the same mechanism.
cout << "Are you enjoying cs161? (1 for yes, 0 for no) " << endl;
Of course, always validate input operations before proceeding to use the data.
if ( !(cin >> ans) )
{
// Input failed. Add code to deal with the error.
}
So I've been reading a C++ Primer that has all kinds of examples and test scenarios inside that are good to make sure each new chapter has been correctly learnt and that there's no other way to improve that actually coding.
The C++ Primer asked for this "Practice Problem" to be attempted and is as follows:
Write a program that provides the option of tallying up the results of a poll with 3 possible values. The first input to the program is the poll question; the next three inputs are the possible answers. The first answer is indicated by 1, the second by 2, the third by 3. The answers are tallied until a 0 is entered. The program should then show the results of the poll—try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered.
So I was curious as to how the author wanted me to make sure that the results fit the screen resolution regardless of "how many results were entered" and after entering the main syntax for the loops that input the data and display. I was curious what the best way to go about this and slapped together a very, VERY simple work around that'll divide by a 1:10 ratio dependant on the highest result input (up to 1000/100)
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Variable decleration
string Question;
int tally1 = 0, tally2 = 0, tally3 = 0;
int input = 1;
int resultRatio;
//Question input and text fluff
cout << "Please enter a poll that has 3 answers: ";
getline(cin, Question, '?');
cout << "Your question is: " << Question << "?" << endl;
cout << "When results are complete for specified poll answer, enter 0 to input results" << endl;
while (1) //Tally 1 answer input.
{
cout << "Please enter the tallies for answer A: ";
cin >> input;
tally1 = tally1 + input;
if (input != 0)
{
cout << "A's current tallies: " << tally1 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 2 answer input.
{
cout << "Please enter the tallies for answer B: ";
cin >> input;
tally2 = tally2 + input;
if (input != 0)
{
cout << "B's current tallies: " << tally2 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 3 answer input.
{
cout << "Please enter tallies for answer C: ";
cin >> input;
tally3 = tally3 + input;
if (input != 0)
{
cout << "C's current tallies: " << tally3 << endl;
continue;
}
cout << endl;
break;
}
// Ratio in which total tallies should be divded by before bar chart display
if (tally1 >= 10 || tally2 >= 10 || tally3 >= 10)
{
resultRatio = 10;
}
else if (tally1 >= 100 || tally2 >= 100 || tally3 >= 100)
{
resultRatio = 100;
}
else if (tally1 >= 1000 || tally2 >= 1000 || tally3 >= 1000)
{
resultRatio = 1000;
}
else
{
resultRatio = 1;
}
//Simple bar chart to display all the results in a ratio that'll fit the screen thanks to resultRatio division
cout << "All results have been entered, here is the barchart (Results displayed are divided by " << resultRatio <<"):";
cout << endl << "A:" << "(" << tally1 << "votes )";
for (int i = tally1 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "B:" << "(" << tally2 << "votes )";
for (int i = tally2 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "C:" << "(" << tally3 << "votes )";
for (int i = tally3 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << "\nHere is the full bar graph on input results";
return 0;
}
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 6 years ago.
Improve this question
I am new to programming and I need help with my term project. I have made a program that simulates a hotel booking, the problem is that whenever a non-whole number is entered for the first question, it goes into an infinite loop. If you get to the second question and enter a non-whole number it accepts it as a whole number by dropping off anything that comes after the decimal and then skips the next question and stops running the program.
#include <iostream>
#include <string>
using namespace std;
int stay_length (int stay)
{
int nights = stay;
int total = 0*nights;
return total;
}
int rooms_booking(int rooms)
{
int rooms_booked = rooms;
int total = 0;
if(rooms_booked > 0)
{
total = rooms_booked * 50;
}
else
{
total = 0;
}
return total;
}
int main(){
int x;
string repeat;
int nights;
int total = 0;
int rooms_avail = 10;
int rooms;
cout << "Hello! Welcome to Hotel COMP 150." << endl;
do {
if (rooms_avail > 0) {
cout << "How many nights will you be staying?" << endl;
}
else {
cout << "Sorry, but there are no rooms available. " << endl;
}
do {
cin >> nights;
if (nights > 0 && nights <= 28)
{
int total1 = stay_length(nights);
cout << "You are staying for " << nights << " nights" << endl;
cout << "That costs: $" << total1 << endl;
total = total + total1;
}
else
{
cout << "You cannot stay less than 1 or more than 28 nights" << endl;
}
} while (nights <= 0 || nights >28);
if (rooms_avail > 0)
{
cout << "How many rooms will you be booking?" << endl;
cout << "There are " << rooms_avail << " available." << endl;
cin >> rooms;
if (rooms > 0 && rooms <= rooms_avail)
{
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else if (rooms <= 0 || rooms > rooms_avail)
{
do{
cout << "You can only book a minimum of 1 room or a maximum of " << rooms_avail << endl;
cin >> rooms;
} while (rooms <= 0 || rooms > rooms_avail );
int total2 = rooms_booking(rooms);
cout << "You are booking " << rooms << " rooms." << endl;
cout << "That costs : $" << total2 << endl;
total = total + total2;
rooms_avail = rooms_avail - rooms;
}
else
{
cout << "You cannot book more than " << rooms_avail << endl;
}
}
else
{
cout << "Sorry, all rooms have been booked." << endl;
}
cout << "Your total so far is: $" << total << endl;
cout << "Would you like to make another booking? Enter 'Y' or 'y' to do so." << endl;
cin >> repeat;
}while(repeat == "Y" || repeat == "y");
return 0;
}
It's always better to use std::getline() instead of operator>> to read interactive input from std::cin.
operator>> is not for reading a single line of text from standard input, and storing it. That's what std::getline() is for.
If the wrong kind of input is entered, not what operator>> expects, it sets std::cin to a failed state, which makes all future attempts to read std::cin immediately fail, resulting in the infinite loop you are observing.
To do this correctly, it is going to be either:
1) Always check fail() after every operator>>, to see if the input failed, if so recover from the error with clear(), then ignore(). This gets real old, very quickly.
2) It's much easier to read a single line of text with std::getline(), then parse the input yourself. Construct a std::istringstream, if you wish, and use operator>> with that, if that makes it easier for you.
You can achieve basic user-input error checking via the console with something along these lines:
int nights = 0;
// error checking loop
while(1) {
std::cout << "How many nights will you be staying?" << endl;
std::cin >> nights;
// input valid
if(!std::cin.fail() && (std::cin.peek() == EOF || std::cin.peek() == '\n')
&& nights > 0 && nights <= 28) {
// do stuff
break; // break from while loop
}
// input invalid
else {
std::cin.clear();
std::cin.ignore(256, '\n');
std::cout << "An input error occurred." << std::endl;
}
}
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 8 years ago.
Improve this question
Hi I am having an unknown issue with getline(). My program is supposed to cout a prompt and then getline() should read in the user input but for some reason every time I run it just couts the prompt and skips to the next prompt, not allowing for me to input anything. I'll post the code and hopefully you guys can offer some advice.
int main()
{
int students = 0;
students = getStudents(students);
int quizzes = 0;
quizzes = getQuizzes(quizzes);
string studentArray[50];
int* quizArray = new int[quizzes];
double* studentAverage = new double[students];
string studentName = "";
for(int i = 0; i < students; i++)
{
cout << "Enter the students name: ";
getline(cin, studentName);
studentArray[i] = studentName;
cout << studentName;
for(int j = 0; j < quizzes; j++)
{
cout << "Enter quiz " << j+1 << ":";
cin >> quizArray[j];
}
studentAverage[i] = calculateAvergage(quizArray,quizzes);
cout << studentArray[i];
cout << studentName;
}
cout << endl;
cout << "Student Quiz Average" << endl << endl;
cout << "---------------------------------" << endl << endl;
for(int i = 0; i < students; i++)
{
cout << studentArray[i];
cout << setw(10) << studentAverage[i] << endl << endl;
}
}
int getStudents(int students)
{
cout << "How many students? ";
cin >> students;
cout << endl;
if(students > 50)
{
cout << "Invalid number of students, enter a number less than 50: ";
cin >> students;
cout << endl;
}
return students;
}
int getQuizzes(int quizzes)
{
cout << "How many quizzes? ";
cin >> quizzes;
cout << endl;
if(quizzes > 10)
{
cout << "Invalid number of quizzes, enter a number less than 10: ";
cin >> quizzes;
cout << endl;
}
return quizzes;
}
double calculateAvergage(int quiz_array[],int num_quizzes)
{
double average = 0;
for(int i = 0; i < num_quizzes; i++)
{
average = quiz_array[i] + average;
}
average = (average/num_quizzes);
return average;
}
Reading single values from a stream like this
cin >> quizzes;
does not consume the trailing end of line character (or any other invalid characters that were left over after attempting to read quizzes), so the next call to getline will continue reading from the same line of input (usually you would expect the line to be empty after reading quizzes, so getline ends up reading nothing).
Your program should work if use the following after reading quizzes:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
or you can just simply read studentName in the same way as the other values
std::cin >> studentName;
As with all calls to operator>> this strips all leading whitespace including newlines.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am taking an integer as input in a string that is string s. I want to write integer in s in the form of "-"'s and "|". I am sure that my logic is right. The problem is string s is automatically getting modified inside the code. When I initially print the string s, it returns complete 12345 (My input is "2 12345") but when I tries to print it afterwards it is getting truncated or something. How do I resolve this?
#include <iostream>
#include <string>
using namespace std;
int main(){
int n;
std::string s;
cin >> n;
cin >> s;
cout << s.at(3) <<endl;
while(n!=0){
for (int l=0;l<3+2*n;l++){
// for (int i=0;i<s.length();i++){
if (l==0){
for (int j=0;j<s.length();j++){
if (s.at(j)=='1'||s.at(j)=='4'){
cout << " ";
for (int k=0;k<n;k++){
cout << " ";
}
cout << " ";
}
else if (s.at(j)=='0'||s.at(j)=='2'||s.at(j)=='3'||s.at(j)=='5'||s.at(j)=='6'||s.at(j)=='7'||s.at(j)=='8'||s.at(j)=='9'){
cout << " ";
for (int k=0;k<n;k++){
cout << "-";
}
cout << " ";
}
cout << " ";
}
}
else if (l==n+1){
for (int j=0;j<s.length();j++){
if (s.at(j)=='1'||s.at(j)=='7'||s.at(j)=='0'){
cout << " ";
for (int k=0;k<n;k++){
cout << " ";
}
cout << " ";
}
else if (s.at(j)=='2'||s.at(j)=='3'||s.at(j)=='4'||s.at(j)=='5'||s.at(j)=='6'||s.at(j)=='8'||s.at(j)=='9'){
cout << " ";
for (int k=0;k<n;k++){
cout << "-";
}
cout << " ";
}
cout << " ";
}
}
else if (l==2*n+2){
for (int j=0;j<s.length();j++){
if (s.at(j)=='1'||s.at(j)=='4'||s.at(j)=='7'){
cout << " ";
for (int k=0;k<n;k++){
cout << " ";
}
cout << " ";
}
else if (s.at(j)=='0'||s.at(j)=='2'||s.at(j)=='3'||s.at(j)=='6'||s.at(j)=='8'||s.at(j)=='9'||s.at(j)=='5'){
cout << " ";
for (int k=0;k<n;k++){
cout << "-";
}
cout << " ";
}
cout << " ";
}
}
else if ((l>0) && (l<n+1)){
for (int j=0;j<s.length();j++){
if (s.at(j)=='1'||s.at(j)=='2'||s.at(j)=='3'||s.at(j)=='7'){
cout << " ";
for (int k=0;k<n;k++){
cout << " ";
}
cout << "|";
}
else if(s.at(j)='4'||s.at(j)=='8'||s.at(j)=='9'||s.at(j)=='0') {
cout << "|";
cout << "s "<< s<< endl;
cout << "check 2";
for (int k=0;k<n;k++){
cout << " ";
}
cout << "|";
}
else if(s.at(j)=='5'||s.at(j)=='6'){
cout << "|";
cout << "check";
for (int k=0;k<n;k++){
cout <<" ";
}
cout << " ";
}
cout << " ";
}
}
else if ((l>n+1) && (l<2*n+2)){
for (int j=0;j<s.length();j++){
if (s.at(j)=='1'||s.at(j)=='3'||s.at(j)=='5'||s.at(j)=='7'||s.at(j)=='9'||s.at(j)=='4'){
cout << " ";
for (int k=0;k<n;k++){
cout << " ";
}
cout << "|";
}
else if(s.at(j)='6'||s.at(j)=='8'||s.at(j)=='0') {
cout << "|";
for (int k=0;k<n;k++){
cout << " ";
}
cout << "|";
}
else if(s.at(j)=='2'){
cout << "|";
for (int k=0;k<n;k++){
cout <<" ";
}
cout << " ";
}
cout << " ";
}
}
cout << s << endl;
cout << endl;
}
cin >> n;
cin >> s;
}
}
else if(s.at(j)='4'||
You forgot an = sign.
A quick look reveals that s.at(j)='6' and s.at(j)='4' modify your string. You can avoid this by using Yoda Conditions.
There are compilers that may warn you about an assignment, here. (See comments).
Also see Mats Petersson's answer, which I consider to be the best adivce: Use const objects, references or pointers to const memory if you do not want to alter contents in a certain situation.
If you'd use a function that takes a std::string const &s for it's argument, doing the job, you'd end up having
cleaner code structure and
compiler errors upon alteration of your argument s.
If you have a situation where you want to avoid unintentionally modifying a variable (for example a string), you can either break out the relevant code into a function and pass a const string& x to the function, or you can create a local const reference. In your code, one could do:
std::string ms;
cin >> n;
cin >> ms;
const &std::string s = ms;
Now you will get an error any time you try to make changes to s, because it's a const.