c++ variable reassignment gets ignored by code [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 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.

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?

Why the loop only run one time? [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 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?".

g++ compiling and while loop [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
Prerequisites: Atom as code editor with gpp-compiler(plugin), that uses g++ to compile and run cpp files in the editor.
Some not real example code to understand the problem:
int main()
{
int number;
while(cin >> number)
{
cout << "Your number is " << number << endl;
}
}
So this program can easily compile by g++ compiler, the problems appears at runtime, when compiled program starts in terminal and... It's just don't work. There is no something else but "Press any key to continue..." There is no even mistakes.
So the compiler cannot support this loop argument? (while(cin>>number))
And yes, gpp-compiler in Atom works fine with other types of scripts.
Sorry, if this question is stupid but i just want to know why this happens. Thank you!
Some edits:
So yeah. I can't competently explain my problem. So my problem is not the while loop argument, i just don't understand why program starts in empty terminal(with message above), while on my phone it also compiles by g++ and the program works perfectly .-.
The (cin >> number) condition always evaluates to true until you send an EOF character to it. On Windows it is Ctrl + Z. The reason you are not seeing anything on standard output is that the program waits for your to enter a value and press Enter. Afterwards it enters the endless loop. Modify your program to include some simple logic:
#include <iostream>
int main() {
char choice = 'y';
int number;
while (std::cin && choice == 'y') {
std::cout << "Enter the number: ";
std::cin >> number;
std::cout << "Your number is " << number << std::endl;
std::cout << "Repeat? y / n: ";
std::cin >> choice;
}
}

clearing out extra input from terminal

Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.

C++: Counting the frequency of ASCII characters in file [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 8 years ago.
Improve this question
I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.
I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.
Here's what I have so far (it's not much and only reads the characters from the file):
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(void)
{
ifstream inputFile;
string infile;
char ch;
//char ascii;
//int asciiArray[128] = {0};
// Gets input filename from user, checks to make sure it can be opened, and then
// gets output filename from user.
cout << "Please enter your input filename: ";
cin >> infile;
inputFile.open(infile.c_str());
if (inputFile.fail())
{
cout << "Input file could not be opened. Try again." << endl;
exit(0);
}
// Gets the first character of the input file.
inputFile.get(ch);
while(!inputFile.eof())
{
inputFile.get(ch);
}
// Closes the input file
inputFile.close();
return 0;
}
Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!
Edit: I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!
You should write your loop as:
while(inputFile >> ascii)
{
asciiArray[ascii]++;
}
Note that I don't directly check for eof in the loop condition since that's almost always wrong.
Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.
In regular Ascii you have 128 chars... of which each char can be evaluated as an int.
That is the key in solving this puzzle.
Just remember you have 128 possible chars, an array with 128 values, and each char represents a number from 0-127.
Also recall that you can do stuff like this:
int i = 97;
char a = i;
char b = a + 1;
cout << (int)i << (int)a << (int)b << endl;
// 979798
cout << (char )i << (char )a << (char )b << endl;
// aab
cout << i << a << b << endl;
// 97ab
As far as pointers go, the only way I would see them as being used is if you used pointer notation instead of array notation while manipulating your variable asciiArray