When running the code to solve for the counting operations the answer will always come out to 3 operations. Why does count always output 3 even when it does not fit the criteria?
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i) + input2.at(i));
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
There is internal typecasting being done here. From char to int as the result is required is in integer format and addition is being done. Therefore actually ASCII values are being added. For '0' it is 48. Therefore everytime the sum is greater than 9. And hence output is 3. The answer here will provide a better insight.
For your question this is a better way to do it. (subtract '0' from each digit char), therefore actually internally it becomes ASCII(digit) - ASCII(0), which will give you the actual digit
#include <string>
#include <iostream>
using namespace std;
int main() {
string input1;
string input2;
cout << "Enter first number: ";
cin >> input1;
cout << endl;
cout << endl;
cout << "Enter second number: ";
cin >> input2;
int count = 0;
for (int i = 0; i < 3; i++) {
int thing = (input1.at(i)-'0') + (input2.at(i)-'0');
if (thing > 9) {
count++;
}
}
cout << count;
return 0;
}
If you are doing mathematical operation you must use appropriate types for the variables. Since you have used strings as variable type , it will not give correct result as desired. For the given code to work try this.
int input1;
int input2;
For more examples on user inputs in c++
Related
I want to enter a eleven-digit number in my variable - number, but I think there's not so much memory. I tried to use *number and int *number = new int[100], but it's not working.
I also want to add name and lastname in my variable - name, but everytime I use space, it's stops working too.
How I can solve these problems?
#include <iostream>
#include <string>
using namespace std;
struct NOTE {
string name;
int number;
int birthday[3];
};
int main()
{
//int *tel = new int[100];
//int *ptr = new int;
NOTE arr[3];
cout << "Please enter quality names and numbers or program stop working!";
for (int i = 0; i < 3; i++) {
cout << "Man #" << i + 1 << "\n";
cout << "Name: ";
cin >> arr[i].name;
cout << "Number: ";
//*tel = arr[i].number;
//cin >> *tel;
cin >> arr[i].number;
cout << "Year: ";
cin >> arr[i].birthday[0];
cout << "Month: ";
cin >> arr[i].birthday[1];
cout << "Day: ";
cin >> arr[i].birthday[2];
}
}
You are currently using a signed integer to hold your value.
int number;
A signed int can hold a maximum value of 2^31 (2,147,483,648), which is only 10 digits long.
unsigned int number;
An unsigned integer can hold 2^32 which is 4,294,967,296 (still 10 digits), which still isn't enough.
You can use a signed long, which is 64 bits in size and can hold a maximum of 2^63 (9,223,372,036,854,775,808), which is 19 digits long. That should suffice.
long number;
forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}
This is my first post on here so please don't kill me for my noobishness.
I recently made a program for fun to put in a ton of numbers and have it put out the mean, not very useful but I thought I would see if I could. I would love it if someone could explain to me how I could improve my code using arrays instead of lots of variables, but still achieve the same thing, maybe even more efficiently.
My code looks like this:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int q1;
int q2;
int q3;
int q4;
int q5;
int q6;
int q7;
int q8;
int q9;
int q10;
int q11;
int q12;
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
cin >> q1;
cin >> q2;
cin >> q3;
cin >> q4;
cin >> q5;
cin >> q6;
cin >> q7;
cin >> q8;
cin >> q9;
cin >> q10;
cin >> q11;
cin >> q12;
f = q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12;
cout << f / a << '\n';
system("pause");
}
Any advice is very appreciated! This was made in Visual Studio just in case you needed to know.
Of course arrays can make your life easier!
Here's how you could have accomplished the same task as above, with arrays:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "You can only enter up to 12 numbers;
// Declare an array to hold 12 int's
int nums[12];
// i will count how many numbers have been entered
// sum will hold the total of all numbers
int i, sum = 0;
for(i = 0; i < 12; i++) {
cout << "Enter the next number: ";
cin >> nums[i];
sum += nums[i];
}
cout << "The mean is: " << (sum / totalNums) << '\n';
//Try to avoid using system!
system("pause");
}
But, why use an array?
There's no need to keep any of the numbers after you add them to the total, so why use an array?
You can accomplish the same task without an array and with only one variable for the numbers!
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int totalNums;
cout << "We will be finding a mean.\n";
cout << "Enter the amount of numbers that will be entered: ";
cin >> totalNums;
// i will count how many numbers have been entered
// sum will hold the total of all numbers
// currentNum will hold the last number entered
int i, sum = 0, currentNum = 0;
for(i = 0; i < totalNums; i++) {
cout << "Enter the next number: ";
cin >> currentNum;
sum += currentNum;
}
cout << "The mean is: " << 1.0 * sum / totalNums << '\n';
//Try to avoid using system!
system("pause");
}
Arrays can be considered as series of variables each of which has ids.
integers between 0 and (number of elements) - 1 (both inclusive) are available ids.
Using that with loop, your code can be like this (sorry, I hate stdafx.h):
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int q[12];
int f;
//Used for the total of all values
int t;
//Used for the total to be divided
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
for (int i = 0; i < 12; i++) {
cin >> q[i];
}
f = 0;
for (int i = 0; i < 12; i++) {
f += q[i];
}
cout << f / a << '\n';
system("pause");
}
You may use the numbers read in the future, but currently the numbers aren't used except for calculating the sum, so you can omit the array and do addition while reading. Also I deleted the variable t, which is unused and stopped using using namespace std;, which is not considered as good.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
int main() {
int q;
int f;
//Used for the total of all values
int a;
//Used for dividing the numbers.
cout << "We will be finding a mean. Enter the amount of numbers that will be entered, the maximum is 12: ";
cin >> a;
cout << "Now enter what numbers you want to find the mean for, because the maximum is 12, if you have less than 12, enter 0 for the rest: ";
f = 0;
for (int i = 0; i < 12; i++) {
cin >> q;
f += q;
}
cout << f / a << '\n';
system("pause");
}
You marked this question as C++.
I recommend you do not use "using", and you should prefer vector over array.
Consider the following approach:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::cout << "We will be finding a mean." << std::endl
<< "Enter numbers, and press ^d when complete.\n"
<< std::endl;
// Declare a vector to hold user entered int's
std::vector<int> intVec;
// the vector automatically keeps track of element count
do {
std::cout << "number: "; // prompt
int t = 0;
std::cin >> t; // use std::cin,
if(std::cin.eof()) break; // ^d generates eof()
intVec.push_back(t);
}while(1);
// there are several way to sum a vec,
// this works fine:
int sum = 0;
for (auto i : intVec) sum += i;
std::cout << "\n sum : " << sum
<< "\ncount : " << intVec.size()
<< "\n mean : " << (sum / intVec.size()) << std::endl;
return(0);
}
You can enter single item per line (neatness counts).
You can enter multiple integers separated by white space, but the above will give back a prompt for the integers already entered.
^d - generates an end of file input.
... press and hold 'Control' key and letter 'd' at same time
Note - does not handle error input - try entering a 'number' as 'num' string.
The accepted answer is definitely the most efficient way to transform your code using arrays, but one thing I would add is that in C++ dividing an integer by another integer can only ever result in an integer, and because you're trying to get the mean, it seems like you'd want to have the result in decimals, so you need to do one of two things:
Declare sum as a float for the purposes of diving it by totalNums to get the mean.
Cast one of the integers to either a float or a double so that the decimals won't get truncated, so the last cout statement would look like this:
cout << "The mean is: " << (double)sum/totalNums << endl;
In C++ the default for precision is 6, but you can change the number of decimal points that are displayed by adding #include <iomanip> and using the setprecision( ) function in the iomanip, which you can just add in the same output line:
cout << setprecision(x) << "The mean is: " << (double)sum/totalNums << endl;
where x is whatever precision you want.
If you want to try using dynamic memory
This is definitely not necessary for what you're doing, but it's interesting stuff and good practice!
One more thing is that if you want to be able to have the user enter integers indefinitely, you can dymanically allocate memory during runtime by declaring a array of pointers to integers (so it's an array of address locations instead of an array of integers) and some sentinal value so they can decide when to stop. That code would look like:
#include <iostream>
#include <iomanip>
using namespace std;
main( ) {
const int ARRAY_SIZE = 200;
const int SENTINAL = -999;
int totalNums = 0;
int sum = 0;
//declare an array of pointers to integers so
//the user can enter a large number of integers
//without using as much memory, because the memory
//allocated is an array of pointers, and the int
//aren't allocated until they are needed
int *arr[ARRAY_SIZE];
cout << "We will be finding a mean." << endl;
cout << "Enter integers (up to 200) or enter -999 to stop" << endl;
//add a conditional into the for loop so that if the
//user enters the sentinal value they will break out
//of the loop
for (int c = 0; c < ARRAY_SIZE; c++) {
//every time you iterate through the loop, create a new
//integer by using the new keyword using totalNums as
//the index
arr[totalNums] = new int;
cout << "Enter integer: ";
//input into the array of pointers by dereferencing it
//(so it refers to what the pointer is pointer to instead
//of the pointer)
cin >> *arr[totalNums];
if (*arr[totalNums] == SENTINAL)
break;
else {
sum += *arr[totalNums];
totalNums++;
}
}
cout << setprecision(3) << "The mean is: " << (float)sum / totalNums << endl;
}
Ok thank you everyone for your comments. I have fixed much of it. Now when I compile it, it gives me an error on line in main where I call getPercent() saying this :
error: cannot convert ‘std::string’ to ‘std::string*’ for argument ‘3’
to ‘void getPercent(int, std::string*, std::string*, std::string*)’
What can fix this?
#include <iostream>
#include <string>
using namespace std;
string getYours()
{
cout << "Enter your DNA sequence: " ;
string sequence;
cin >> sequence;
return sequence;
}
int getNumber()
{
cout << "Enter the number of potential relatives: ";
int number;
cin >> number;
cout << endl;
return number;
}
void getNames(int number, string name[])
{
for (int i = 0; i < number; i++)
{
cout << "Please enter the name of relative #" << i + 1 << ": ";
cin >> name[i];
}
}
void getSequences(int number, string name[], string newsequence[])
{
cout << endl;
for (int i = 0; i < number; i++)
{
cout << "Please enter the DNA sequence for " << name[i] << ": ";
cin >> newsequence[i];
}
}
void getPercent(int number, string name[], string sequence[],
string newsequence[])
{
cout << endl;
int count = 0;
for (int i = 0; i < number; i++)
{
if (sequence[i] == newsequence[i])
count = count + 10;
cout << "Percent match for " << name[i] << ": " << count << "%";
}
}
int main()
{
string sequence = getYours();
int number = getNumber();
string name[50];
string newsequence[50];
getNames(number, name);
getSequences(number, name, newsequence);
getPercent(number, name, sequence, newsequence);
return 0;
}
A few problems:
getYours() has no side effects. You probably meant to assign to the string sequence in main(), but instead are assigning to a local variable that will be destroyed as it goes out of scope.
No error checking for too many elements in your arrays (try using a std::vector).
You stop at 10 in getPercent() instead of number elements (if that's what you wanted).
In getPercent(), count is not initialized to 0. Something seems strange about the logic in getPercent(), so I am not exactly sure what you are trying to do.
The arguments sequence and newsequence in getPercent() are actually the same type, and would compile fine.
And probably a few other things I've overlooked.
I am trying to do a modulus operation. I ask the user to input two numbers, since modulus only works with integers, I have a while loop that checks if the inputs are integers. Then the while loop ask the user to re-enter the two numbers. But the while loop keeps on repeating and does not allow the user a chance to re-enter the numbers. What will be the proper to go about doing this?
#include <iostream>
using namespace std;
int Modulus (int, int,struct Calculator);
struct Calculator
{
int per_numb1, per_numb2;
int per_Result; };
int main ()
{
Calculator Operation1;
cout << "\nPlease enter the first number to calculate as a modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease enter the second number to calculate modulus: ";
cin >> Operation1.per_numb2;
while ( !( cin >> Operation1.per_numb1) || !( cin >> Operation1.per_numb2))
{
cout << "\nERROR\nInvalid operation \nThe first number or second number must be an integer";
cout << "\n\nPlease re-enter the first number to begin Modulus: ";
cin >> Operation1.per_numb1;
cout << "\nPlease re-enter the second number to begin Modulus: ";
cin >> Operation1.per_numb2;
}
Operation1.per_Result = Modulus(Operation1.per_numb1, Operation1.per_numb2, Operation1);
cout << "\nThe result is: " << Operation1.per_Result << endl;
}
int Modulus (int n1, int n2, struct Calculator)
{
int Answer;
Answer = n1 % n2;
return Answer;
}
Refactor to something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Calculator
{
public:
static int Modulus (int n1, int n2);
};
int Calculator::Modulus (int n1, int n2)
{
return n1 % n2;
}
int getInt(string msg)
{
int aa;
cout << msg;
cin >> aa;
while (cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
cerr << "Input was not an integer!" << endl;
cout << msg;
cin >> aa;
}
return aa;
}
int main ()
{
int num1 = getInt("Enter first value: ");
int num2 = getInt("Enter second value: ");
int value = Calculator::Modulus(num1,num2);
cout << "Answer:" << value << endl ;
}
When the input parsing fails, invalid input data will remain in the stream. You need to
clear the stream error state by calling cin.clear().
and skip the remaining invalid input.
See the answer to this question.