Why the loop only run one time? [closed] - c++

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 3 years ago.
Improve this question
I tried to do a phone Sys and I used a while loop in the main{}. I don't know why it only runs one time, it suppose to run infinite time unless I give it command to stop.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void record(string name, int phoneNum, int count);
// main
int main() {
cout << " Welcome to use the Phone Contact Systerm " << endl;
string name;
int phoneNum;
int count = 0;
string signToStop;
cout << " Please enter name and phone number " << endl;
while ( cin >> name >> phoneNum){
cout << " If you want to start the program, enter start " << endl;
cout << " If you want to quit the program, enter quit " << endl;
cin >> signToStop;
if (signToStop == "start"){
record(name, phoneNum, count);
}
else if ( signToStop == "quit" ){
break;
}
count++;
}
}
// record all name info into Name set and record all phone numbers into PhoneNum set
void record(string name, int phoneNum, int count){
string Name[] = {};
int PhoneNum[] = {};
Name[count] = {name};
PhoneNum[count] = {phoneNum};
// now start to record all the info into .txt document
ofstream phoneFile;
phoneFile.open("contact.txt");
phoneFile << name << " " << phoneNum << endl;
}
The result is:
Welcome to use the Phone Contact Systerm
Please enter name and phone number
Molly 5307659229
Process finished with exit code 0

Maybe try ulong int for the phone number, it might be too long. Also I might add that I am a bit confused, as your function record() has a 3rd argument that has no default argument. Your problem might lie there too. As without a default you need to put the argument in when it is used.

As spectras said, a phone number is not really an integer, and so it's not a "number" in the programming (or even mathematical) sense.
It's more like a sequence of digits; that is, a string.
You have two problems when you try to interpret it as an int:
Your int type is too small for the value (this is what's causing your loop to end)
Leading zeroes are not meaningful (at best, it's used to flip into octal mode, which is not what you wanted).
I'd instead read it as a string. You can still validate it later, like "is every character a digit?".

Related

Why is the int function acting strange when I set it to 500? c++ [closed]

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 11 months ago.
Improve this question
I am trying to set a int to 500, but random numbers such as 22067 come out.
I am trying to make a simple gambling game. Currently, what I'm doing is that I set int gambledMoney = 500; But when I ask to print the 500, it does work but instead it prints 22067. Here is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
//introduction
cout << "Why hello human!\nWelcome to this gambling game where you... gamble!\nTo explain how to play here are the steps:\n\n";
//instructuions
cout << "You always start with $2000.\nAt the very beginning of each new round, you will be given choices on the amount of money you will gamble.\n";
cout << "Then you will gamble against an AI.\nIf you win, you gain the amount that the AI gambled...\nBut if you lose, you lose the money that you gambled.\n";
cout << "If you reach $500, you lose. Same goes with the AI.\n";
//game start
cout << "\nNow lets start!\n";
//gamble amount
string gambleChoice;
int gambledMoney;
cout << "\nHow much would you like to gamble?";
cout << "\n A) $500\n B) $750\n C) $1000\n D) $1250\n E) $1500\n F) $1750\n G) $2000\n\n";
//amount chosen
cin >> gambleChoice;
if (gambleChoice == "a")
{
int gambledMoney = 500;
}
cout << "\nYou have gambled $" << gambledMoney << "!" << endl;
return 0;
}
Does anyone know why it is not putting 500?
You are declaring two different variables with the name gambledMoney in different scopes, so that one variable "shadows" the other variable with the same name.
The line
int gambledMoney = 500;
will create a new variable with that name, and set it to 500. It won't change the value of the existing variable to 500.
You probably want to change that line to the following:
gambledMoney = 500;
That way, it will change the value of the existing variable, instead of creating a new one.
If you are using the compilers gcc or clang, I recommend that you compile with the -Wshadow command-line option. That way, the compiler will warn you when you create two variables of the same name, so that one shadows the other.
That is not the only compiler warning that I recommend enabling, though. You may want to read this for further information:
Why should I always enable compiler warnings?

c++ variable reassignment gets ignored by code [closed]

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 2 years ago.
Improve this question
I am not a professional programmer but after getting some experience in easy languages like python or matlab, I need to make a little program in C++. For this I try to read user input until the user inputs something sensible - however, this loop never terminates due to my control variable (test2) never being reassigned, even though the corresponding code block is entered. Let me explain in detail:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Header.h"
using namespace std;
int test2; //variable to stay 1 until user has entered suitable input
string input2[2]; //storage for input strings
int MinimalTest() {
test2 = 1; //control variable is set one
cout << "Enter a string." << endl;
do {
//we will enter a string at least once, and we exit this loop only when the input is suitable
std::string line; //complicated input part - a simple getline() command led to weird behaviour
std::getline(std::cin, line);
std::stringstream linestream(line);
linestream >> input2[i];
cout << "input: " << input2[i] << " test: " << test2 << "input bool: " << input2[i].empty() << endl; //this is just for troubleshooting
if (input2[i].empty()) {
//if the user entered an empty string, he needs to do it again
cout << "Your string is empty. Please enter a valid string (non-empty)." << endl;
}
else {
//if he entered a valid string, we can continue with the next input
cout << "I am here." << endl; //This is for trouble shooting. This code block is entered and executed since this gets printed.
test2 = 0;// this gets ignored for some reason. Hence, the loop never terminates.
}
}(while (test2 = 1);
}
So the first loop never terminates. Test2 never gets reassigned to 0, even though the else command is executed. This boggles my mind tbh - it is just a simple assignment operator on an int. Possible output looks like this (Note how I still got a second problem: strings with a space inside get cut off. I would appreciate any feedback on that as well, even though I try to trouble shoot one thing at a time and this post is not aimed at this problem):
Output example
Thank you very much for your consideration!
All the best,
A very confused newbie.
Change your while condition to test2 == 1
test2 = 1 is an assignment, setting the value to 1.

Beginning C++: using if else, n--, number [closed]

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 5 years ago.
Improve this question
I am struggling to get this program to work. Could someone please look it over to see what is wrong? (The compiler says that sum_positive is not defined in this way.) Also, I have searched this problem and found an answer on here, but I did not see the problem that way and want to avoid plagiarism when I turn in my homework. Thank you!
Write a program that reads in ten whole numbers and that outputs the sum of all the numbers greater than zero, the sum of all the numbers less than zero (which will be a negative number or zero), and the sum of all the numbers, whether positive, negative, or zero. The user enters the ten numbers just once each and the user can enter them in any order. Your program should not ask the user to enter the positive numbers and the negative numbers separately.
Program:
#include <iostream>
using namespace std;
int main()
{
int number, n = 10, sum_positive = 0, sum_negative = 0, sum = 0;
int count = 0, positive_count = 0, negative_count = 0;
cout << "Please enter in 10 whole numbers, one at a time." << endl;
do
{
cout << "Please enter another number." << endl;
cin >> number;
n--;
}
while (n > 0);
if (number >= 0)
{
sum_positive += number;
//positive_count++; count++;
}
else
{
sum_negative += number;
//negative_count++; count++;
}
sum = sum_positive + sum_negative;
cout << sum_postive << endl;
cout << sum_negative << endl;
cout << sum << endl;
return 0;
}
there is a spelling mistake in your code of sum_positive in line (cout << sum_postive << endl;) - you have written sum_postive but you declared sum_positive.
you are running a loop and taking input in the same variable number, so it will overwrite all the inputs and will store only the last value in variable number which user entered. So your sum will always be equal to the last value user entered.
For this you need to use an array.
Example:
int number[10], n=10, sum_positive=0;
do{
cout<<"e`enter code here`nter number:";
cin>>number[n];
n--;
}while(n>0);
now for sum also you need to use an loop.
If you do not know about an array, study about it how to use it.

How to convert first letter to uppercase in c++? [closed]

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 5 years ago.
Improve this question
I have a Structure
struct StudentRecord{
char StudentFamilyName[20]
}gRecs[50];
cout << "Family Name: ";
cin >> gRecs[50].StudentFamilyName;
char str[20];
str[20] = toupper(gRecs[i].StudentFamilyName[0]);
cout << str;
What i want to do is to store the first letter of family name as
upper case and the rest as lower case? How do I do that?
I used toupper but when I implement it doesnot work. Could anyone help me out? Thank you.
Note: This was an exam question.
Here's how to capitalize a string using character arithmetic:
#include <iostream>
#include <string>
using namespace std;
string ToCapitalize(string input)
{
if (input.length() > 1 && input[0] >= 'a' && input[0] <= 'z')
{
input[0] -= 32;
}
return input;
}
int main() {
std::string StudentFamilyName("smith");
cout << StudentFamilyName << std::endl;
cout << "Capitalized: " << ToCapitalize(StudentFamilyName) << endl;
}
Your problem isn't with toupper. There are a couple of them, actually.
cin >> gRecs[50]
gRecs is size 50, so index 50 is out of bounds. To insert into the first record you would use
cin >> gRecs[0].StudentFamilyName;
Second record: gRecs[1], etc.
Next,
char str[20];
str[20] = toupper(str[0]);
You declare str in which nothing is populated, and then call toupper on it.
And the index ([20]) is the 21st character (which is out of bounds). You are attempting to convert the 21st character in the str toupper.
What you need is something like:
// i is the index into your student records array, possibly in a loop
cin >> gRecs[i].StudentFamilyName;
gRecs[i].StudentFamilyName[0] = toupper(gRecs[i].StudentFamilyName[0]);

new structure crashing in console, why? [closed]

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
This will crash console only if I ask the user to input pizza diameter before name.
If i ask for pizza name and then ask for pizza diameter and weight it seems to work fine - this i dont get why.
#include <iostream>
using namespace std;
struct pizza_structure
{
double diameter;
char name[100];
double weight;
};
int main()
{
pizza_structure * ps = new pizza_structure;
cout << "Enter pizza diameter: ";
cin >> ps->diameter;
cout << "Enter pizza name: ";
cin.get(ps->name, 100);
cout << "Enter pizza weight: ";
cin >> ps->weight;
cout << "Name: " << ps->name << ", diameter: " << ps->diameter << ", weight: " << ps->weight;
delete[] ps;
cin.get();
cin.get();
return 0;
}
You are mixing types of input between formatted using cin >> ... and unformatted using cin.get(...)
This goes "wrong" because the formatted input leaves the newline in the input buffer, which is then read as the first character for cin.get(...) - meaning the string is empty, and then when you read weight, it fails to read properly.
You will need to either read the extra newline with a spare cin.get() [and hope the user didn't add a some non-digit character to the input] or manually parse the input using getline and splitting the line yourself [e.g. using stringstream to read out the digits from the line].
Commercial grade UIs will certainly use custom read functions that are more meaningful when it comes to input errors too.
As others have said delete [] is wrong - and in fact there is no reason to use new in the first place for such a small structure.