User input in simple C++ counter program - c++

I'm trying to make a simple counter program in C++ that will increment a variable with user input (specified by pressing a certain key). Here is what I came up with:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
int variable;
char userInput;
variable = 0;
cout << "To increment variable one, press a \n";
do
{
variable = variable++;
cout << "variable++ \n" ;
} while (userInput = "a");
}
I have perused several related threads on this site and believe this should work. However, I get several errors, including that the operation on variable is not defined and that there has been an "invalid conversion" from "const char" to "char."

Add cin in your loop:
cin>>userInput;
and change
variable = variable++;
to
variable++; // or variable = variable + 1;
next you while condition should be like this:
while (userInput=='a');
So your overall program will look like this:
#include <iostream>
using namespace std;
int main()
{
int variable;
char userInput;
variable = 0;
cout << "To increment variable one, press a \n";
do
{
cin>>userInput;
variable++;
cout << "variable++ \n" ;
} while (userInput=='a');
return 0;
}

In while loop you need a std::cin, like
cin >> userInput;
Moreover, the following line
variable = variable++;
will produce Undefined Behaviour. Read more about Sequence point for better understading.
Try:
variable = variable + 1;
Finally in the while loop breaking condition, instead of assignment operation
while (userInput = "a");
Use comparison like:
while (userInput == "a");

You need to use
std::cin >> userInput; // each time you go through the `do` loop.
Also, you just need to use
variable++; // on the line.
Also! Use cout << variable << "\n";
Lastly, use
} while(strncmp((const char*)userInput,(const char*)"a",1));

Related

C++ Loop for String

I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}

Does it matter where I initialize my integer?

I'm trying to understand something. I'm still a beginner to c++ and I just created this little program where you input a value and it tells you whether it's even or odd. To do this, I made an integer called "result" which takes value, and then does % 2 operation.
However, my first mistake was that I put int result above "cin >> value" so for some reason that messed up the program and the number would always be even no matter what. Then when I put int result below "cin >> value" the program worked like it should. Why is it doing this?
Any help would be appreciated thank you. I apologize if this is a duplicate but I don't know what to search for.
#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;
int main() {
int value = 0; // where I input
cin >> value;
// if you put int result above cin program changes.
int result = value % 2;
if (result == 0) {
cout << "Even number." << endl;
}
else {
cout << "Odd number." << endl;
}
return 0;
}
Any code whichever programming language you use runs from top to bottom.
You need to first declare the variable, give it a value and then check for being even or odd.
When you used cin after setting the value of result = value%2; the compiler used the originally initialized value for value which is 0 to compute the value of result which will be 0%2.
That's why you need to use cin>>value; before setting result = value%2;.
C++ read the code top to bottom , line by line. So you will have to int your variable first.I made a much more simpler version of the program if you want to read it:
#include <iostream>
using namespace std;
int main() {
int a;
cout << "a=";
cin >> a ;
if(a%2==0)
{cout<<"a is even";}
else
{cout<<"a is uneven";}
}
When you put int result = value % 2; before cin >> value;, your program will calculate the result before you put a value inside int value via your input.
So your program does calculate int result = 0 % 2;

Can anyone help identify why this wont execute properly? IF promblems with cast

#include <iostream>
#include <fstream>
using namespace std;
int run_t = 0;
char q_mos;
char i_pstring;
int main () {
cout << "Would you like to write to the temporary datapcku database?\nSelect Y/N\n";
cin >> q_mos;
if(q_mos = char(Y)){ //for some reason I am having time resolving the value of Y
while(run_t=0){
cout << "Running Input Operations.\n";
cout << "Please provide me with a Question so it can be achrived in the Active DB(Directory)\n";
cin >> i_pstring;
cout << "Please tell me the answer...\n";
cout << i_pstring;
}
run_t=1;
} else {
run_t=1;
cout << "Booting into main operations...\n";
}
cout << "At diagnostic Boot menu, prepare for diagnostic on system config orginaztional routines.\n";
ofstream binlib;
binlib.open ("datapcku.bin", ios::app | ios::binary );
binlib << "Writing this to a file.\n";
binlib.close();
while(1){}
return 0;
}
As is is apparent I wanted to use my run_t variable to control complete program maneuverability but I am having a time executing q_mos to cin input and I can not understand why the logic appears to be failing, as in the simple while loop following the q_mos comparison wont execute even one I get inside the block.
Do i need to convert q_mos to a string? And what could be affect my run_t variable while loop.
A couple of things are wrong.
In your if(q_mos = char(Y)) statement,
a) you are assigning, not comparing (use == instead of =). This also applies to your while loop.
b) replace char(Y) with 'Y', as you are passing it at the moment, Y is perceived to be a variable.

Super basic code: Why is my loop not breaking?

for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
cout << size;
if(inputnum[i] == '.')
{
break;
}
}
The break breaks the input stream but the size keeps outputting.
The output of size is 012345678910111213...474849.
I tried putting size++ inside the loop but it made no difference. And size afterwards will be equal to 50, which means it went through the full loop.
I forgot to explain that I added the cout << size within the loop to debug/check why it outputted to 50 after the loop even if I only inputted 3 numbers.
I suspect that inputnum is an array of int (or some other numeric type). When you try to input '.', nothing actually goes into inputnum[i] - the cin >> inputnum[i] expression actually fails and puts cin into a failed state.
So, inputnum[i] is not changed when inputting a '.' character, and the break never gets executed.
Here's an slightly modified version of your code in a small, complete program that demonstrates using !cin.good() to break out of the input loop:
#include <iostream>
#include <ostream>
using namespace std;
int main()
{
int inputnum[50];
int size = 0;
for(int i=0;i<50;i++,size++)
{
cin >> inputnum[i];
if (!cin.good()) {
break;
}
}
cout << "size is " << size << endl;
cout << "And the results are:" << endl;
for (int i = 0; i < size; ++i) {
cout << "inputnum[" << i << "] == " << inputnum[i] << endl;
}
return 0;
}
This program will collect input into the inputnum[] array until it hits EOF or an invalid input.
What is inputnum ? Make sure t's a char[]!! with clang++ this compiles and works perfectly:
#include <iostream>
int main() {
int size = 0;
char inputnum[60];
for(int i=0;i<50;i++,size++) {
std::cin >> inputnum[i];
std::cout << size;
if(inputnum[i] == '.') {
break;
}
}
return 0;
}
(in my case with the following output:)
a
0a
1s
2d
3f
4g
5.
6Argento:Desktop marinos$
Your code seams OK as long as you're testing char against char in your loop and not something else.. Could it be that inputnum is some integral value ? if so, then your test clause will always evaluate to false unless inputnum matches the numerical value '.' is implicitly casted to..
EDIT
Apparently you are indeed trying to put char in a int[]. Try the following:
#include <iostream>
int main() {
using namespace std;
int size = 0;
int inputnum[50];
char inputchar[50];
for(int i=0;i<50;i++,size++) {
cin >> inputchar[i];
inputnum[i] = static_cast<int>(inputchar[i]); // or inputnum[i] = (int)inputchar[i];
cout << size << endl; // add a new line in the end
if(inputchar[i] == '.') break;
}
return 0;
}
Then again this is probably a lab assignment, in a real program I'd never code like this. Tat would depend on the requirements but I'd rather prefer using STL containers and algorithms or stringstreams. And if forced to work at a lower-level C-style, I'd try to figure out to what number '.' translates to (simply by int a = '.'; cout << a;`) and put that number directly in the test clause. Such code however might be simple but is also BAD in my opinion, it's unsafe, implementation specific and not really C++.

passing int variables in C++ - error check not returning value

okay so I am trying to check variables when they are input by the user, however they don't seem to stick. now the error check seems to work, but the variable is lost somewhere leaving 'num = 0'
I had copied some of this code from another source but I am not sure where it is going wrong.
I would like to input a number, check if it is an integer, and then return said integer to the variable 'num'.
#include <iostream>
using namespace std;
int checkCin(int var) {//open function
bool ok = false;//set variable to false
while (!ok)/*if variable is false, loop*/ {//open loop
cin >> var;
//this will cheack if anything is in variable other than an integer
if(!cin.fail() && (cin.peek()==EOF || cin.peek()=='\n')) {//open if
ok = true;//this will end loop
return var;
}//close if
//this will clear the cin and ignor whats left - ignoring this part stops an infinate loop cycle
else {//open else
cin.clear();
cin.ignore(256,'\n');
cout << "Error, enter a number" << std::endl;
}//close else
}//close loop
//prepared for next input
ok = false;
}//close function
int main() {
int num = 0;
checkCin(num);
cout << num << endl;
system("pause");
return 0;
}
You are returning the read number from your function by doing
return var;
at some point, but you are not using the result in your main function. You just have
checkCin(num);
in there, which throws away the result. Also, the input argument does not really make sense, because you pass by value and therefore cannot modify the value seen in main inside the function. What you could do is declare checkCin without parameters and assign the return value in main, i.e.
num = checkCin();
This would be most obvious for someone reading your program the first time, because checkCin doesn't need the original value of var and therefore it doesn't need to be passed in.
Another way would be to declare checkCin as taking a reference and returning nothing, i.e. void checkCin(int& var). Then you could keep your code in main, because now the function can actually modify the variable num passed in from main. However, this second solution would be quite uncommon for a function that returns only a single simple piece of data like an int.
Here's a cleaned up version of your code (you also see, with proper indentation, the "open loop", "close loop", etc. comments would not be necessary, because nesting levels are obvious):
#include <iostream>
using namespace std;
int checkCin() {//open function
int var;
while (true) { //open loop
cin >> var;
//this will cheack if anything is in variable other than an integer
if(!cin.fail() && (cin.peek()==EOF || cin.peek()=='\n')) {//open if
return var;
} else { //open else
cin.clear();
cin.ignore(256,'\n');
cout << "Error, enter a number" << std::endl;
} //close else
} //close loop
} //close function
int main() {
int num = checkCin();
cout << num << endl;
system("pause");
return 0;
}