How to store characters in an integer array? [duplicate] - c++

This question already has answers here:
Cout a whole array in c++
(7 answers)
Closed 3 years ago.
I'm trying to implement a function that will parse numbers for a calculator assignment that I have been given. A for loop has been set up that will iterate through each index in the input array which is a arithmetic equation e.g "1+2+3+4+5". I created a function isDigit() that will return true or false if the character is between 0 and 9. This is how I am parsing the numbers. My problem is that the numbers are not being permanently stored in my numbers[] array which I would like to return.
Currently the numbers are being printed to the console with the first cout as "12345" but with the second cout (currently commented) which to check what my returned array stores is an ambiguous hex number. Can someone please help me to return "12345" in numbers[].
int * parseNumbers(char input[])
{
static int numbers[10];
for (int i = 0; i < strlen(input); i++)
{
if (isDigit(input[i]))
{
numbers[i] = input[i] - '0';
cout << numbers[i];
}
}
//cout << numbers << endl;
return(numbers);
}
numbers = 1, 2, 3, 4, 5
currently getting numbers = 002D26E8

I think what you're looking for is atoi to convert char to int.
Instead of using numbers[i] = input[i] - '0';
try this:
numbers[i] = atoi(input[i]);
Make sure to have #include <stdlib.h> if not aready added
Reference: http://www.cplusplus.com/reference/cstdlib/atoi/

Related

String array when assigned to an integer produces a weird value [duplicate]

This question already has answers here:
Why does subtracting '0' in C result in the number that the char is representing?
(8 answers)
Closed 2 years ago.
I'm trying to figure out a code that a friend sent me and I couldn't figure out why this certain code exists.
The goal is that when you type a 3 digit number sequence in string, it converts it to int and prints the sequence in reverse.
string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0];
seconddig = s[1];
thirddig = s[2];
cout << thirddig << seconddig << firstdig;
Here is the problem with this code
When I input "123", the output becomes "515049" instead of "321"
However
This is the code that apparently fixes the problem
string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0] - '0';
seconddig = s[1] - '0';
thirddig = s[2] - '0';
cout << thirddig << seconddig << firstdig;
This time, I input "123", the output becomes "321"
My main question is, where did "515049" come from, and what does the code "- '0'" do?
I don't know what that code does. C++ C++ C++
In the first code, you are converting a char into an int directly which, as it has been pointed out in the comments, gets the ASCII value of the characters.
In the second code, when you substract the ASCII value of the characters and '0' you get the original value of the character.

Problem converting a std::string of digits to vector<int> [duplicate]

This question already has answers here:
C++ handling very large integers
(15 answers)
Closed 3 years ago.
I am supposed to get two big integer numbers (up to 600 digits) from console screen and write the result on the console again.
I defined two variables of type std::string to store two big integer numbers .I take their values from the user. To take the sum of that two numbers, I defined two vectors to store the digits of that two strings of numbers .
Here is the problem, when I try to loop through the vector to print the digits that I took from strings of numbers I get the following result .The Ascii values of the digits are printed on The Console.
Could anyone tell me how to fix this problem please.
Note: The code is still not complete .
For the first string I took the numbers 9 8 7 6 5 4 3 2 1 from the user , on the console window I got the following result.
[0]57
[1]56
[2]55
[3]54
[4]53
[5]52
[6]51
[7]50
[8]49
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::string Sum_Of_Two_Long_Integers()
{
std::string First_String ;
std::string Second_String ;
std::string Result_String ;
std::cout << "Please enter the first number: " ;
std::getline(std::cin, First_String);
std::cout << "Please enter the second number: " ;
std::getline(std::cin, Second_String);
std::vector <int> First_String_Vector (First_String.length()) ;
std::vector <int> Second_String_Vector (Second_String.length()) ;
for(int Counter = 0 ; Counter < First_String_Vector.size() ; ++ Counter)
{
First_String_Vector[Counter] = First_String[Counter] ;
Second_String_Vector[Counter] = Second_String[Counter] ;
std::cout << "[" << Counter << "]" << First_String_Vector[Counter] << std::endl ;
}
return Result_String ;
}
int main()
{
std::string Result_String = Sum_Of_Two_Long_Integers() ;
std::cout << "Result = " << Result_String << std::endl ;
return 0 ;
}
First_String_Vector[Counter] = First_String[Counter] ;
Second_String_Vector[Counter] = Second_String[Counter] ;
The digits are stored as ASCII in you string, you should convert to integer before placing them into the vector.
This would do the trick:
First_String_Vector[Counter] = First_String[Counter] - '0';
Second_String_Vector[Counter] = Second_String[Counter] - '0';
I would also add a check for valid input before populating your vectors to make sure that you only read digits:
if(First_String[Counter] < '0' || First_String[Counter] > '9' ||
Second_String[Counter] < '0' || Second_String[Counter] > '9')
{
std::cout << "Invalid input\n";
return "":// Or better throw an exception
}
EDIT: '6' isn't equal to 6. The first one is a char, its value is ASCII for character '6', and the second is the integer 6.
ASCII is an encoding. Characters are mapped to some numbers. Value for '0' is 48, '1' is 49, ..., '9' is 57
To be even more precise C++ does not guarantee to use ASCII encoding (though I don't know of an implementation that does not use it), but it does guarantee that '0'...'9' have contiguous integer values. So '6' - '0' will give us integer 6.

How can I discover the amount of elements in an array in C++ [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
C sizeof a passed array [duplicate]
(7 answers)
Closed 4 years ago.
I'm facing some problems with my code in C++. I would like to know how can I discover the amount of elements in an array. Follow the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int avg(int numbers[]){
int amount; // The problem is in. How can I discover the amount of elements in an array?
int sum = 0;
for(int i = 0; i < amount; i++){
sum += numbers[i];
}
return sum / amount;
}
int main(){
int q;
cout << "Type number of integers:" << endl;
cin >> q;
int numbers[q];
for(int i = 0; i < q; i++){
cout << "Type an integer value for number " << i+1 << ":" << endl;
cin >> numbers[i];
}
cout << "The average is " << avg(numbers) << endl;
return 0;
}
The standard array in C++ doesn't contain a way to access the size of the array, the best way to track this is to have an integer that is updated with the size of the array or to try using std::array and then use the .size() method.
In your example you are using a fixed size array anyway so you may want to store the q value as a member variable and that contains the array size. Notice that in your example the code will not work as q is not a constant integer. To declare an array without a constant integer you will need to use a pointer to the first element of the array ie: int* numbers = new int[q];.

Beginner code looking for improvements [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I'm very new to C++. The code below is something I made and functions just fine. However, it seems rather long and I feel like it could be reduced - perhaps to increase efficiency.
The purpose of this code is to translate any DNA sequence into its respective amino acid sequence. It includes a portion where the DNA sequence is verified by the user. Three ORFs are generated using the inputted sequence.
Although it is functional, I have some issues with my program.
One, I would like to make the size of the amino acid array (AA_string1, 2, and 3) as large as they need to be. No concrete memory allocation (so I don't have to change the code all the time) and no wasted memory. Could this be accomplished by pointer arrays?
Two, if the user inputs something that is not expected (like a 2 where you were supposed to enter a 1 or 0), my program encounters an "out_of_range" memory error. I believe I could fix this by adding an error message upon invalid input and returning to a line of code just prior to where the error occurred. I attempted using the "goto" command to do this, laying out various labels for where I'd like the code to reset. This doesn't seem to be working. I continue to encounter an out_of_range memory error upon invalid input.
If you guys have any suggestions on the issues I mentioned or the code itself, let me know in the comments below!
P.S. I put asterisks around the lines of code that I mentioned in my issues.
int main()
{
// Key for converting DNA sequence to amino acid sequence.
string codons[64] = { "UUU","UUC","UUA","UUG","UCU","UCC","UCA","UCG","UAU","UAC","UAA","UAG","UGU","UGC","UGA","UGG",
"CUU","CUC","CUA","CUG","CCU","CCC","CCA","CCG","CAU","CAC","CAA","CAG","CGU","CGC","CGA","CGG",
"AUU","AUC","AUA","AUG","ACU","ACC","ACA","ACG","AAU","AAC","AAA","AAG","AGU","AGC","AGA","AGG",
"GUU","GUC","GUA","GUG","GCU","GCC","GCA","GCG","GAU","GAC","GAA","GAG","GGU","GGC","GGA","GGG" };
string aminoAcids[64] = { "Phe(F)","Phe(F)","Leu(L)","Leu(L)", "Ser(S)","Ser(S)","Ser(S)","Ser(S)","Tyr(Y)","Tyr(Y)", "Stop(*)","Stop(*)", "Cys(C)","Cys(C)","Stop(*)", "Trp(W)",
"Leu(L)","Leu(L)","Leu(L)","Leu(L)","Pro(P)","Pro(P)","Pro(P)","Pro(P)","His(H)","His(H)","Gln(Q)","Gln(Q)","Arg(R)","Arg(R)","Arg(R)","Arg(R)",
"Ile(I)","Ile(I)","Ile(I)","Met(M)","Thr(T)","Thr(T)","Thr(T)","Thr(T)","Asn(N)","Asn(N)","Lys(K)","Lys(K)","Ser(S)","Ser(S)","Arg(R)","Arg(R)",
"Val(V)","Val(V)","Val(V)","Val(V)","Ala(A)","Ala(A)","Ala(A)","Ala(A)","Asp(D)","Asp(D)","Glu(E)","Glu(E)","Gly(G)","Gly(G)","Gly(G)","Gly(G)" };
// Variable declaration.
string DNA_string;
*string AA_string1[100];*
*string AA_string2[100];*
*string AA_string3[100];*
// User inputs DNA sequence.
cout << "Enter DNA sequence here: " << endl;
cin >> DNA_string;
cout << "\n";
// Preparing for sequence conversion.
int dnaLength = DNA_string.length();
int numberofCodons = dnaLength / 3;
int i = 0;
int j = 0;
int baseError;
string baseCorrect;
bool isCorrect = 0;
// Verifies if DNA sequence is inputted correctly.
while (isCorrect == 0)
{
// Enters codons into the amino acid string array.
j = 0;
while (j <= numberofCodons)
{
for (i = 0; i <= dnaLength; i += 3)
{
AA_string1[j] = DNA_string.substr(i, 3);
j += 1;
}
}
// Displays the DNA sequence as sets of codons.
for (i = 0; i <= numberofCodons; i++)
{
cout << AA_string1[i] << " ";
// Indicates base position.
if ((i + 1) % 10 == 0)
{
cout << ((i + 1) * 3) << " ";
}
}
*UserVerify:*
// Asks user to verify sequence.
cout << "\nIs the following sequence correct?\n";
cout << "Type 1 for yes and 0 for no: ";
cin >> isCorrect;
*if (isCorrect != 0 && isCorrect != 1)
{
cout << "Invalid Input: Please enter 1 or 0.";
goto UserVerify;
}*
else if (isCorrect == 0)
{
cout << "\nPlease enter the base position you would like to change:
";
cin >> baseError;
cout << "What should the base be changed to? If it should be
deleted, type 0: ";
cin >> baseCorrect;
if (baseCorrect == "0")
{
DNA_string = DNA_string.erase(baseError - 1, 1);
}
else
{
DNA_string = DNA_string.replace(baseError - 1, 1, baseCorrect);
}
}
cout << "\n";
}
*DNA_Conversion:*
// Converts DNA sequence into AA sequence over three ORFs.
// computeORF is a void function I made.
computeORF(AA_string1, 0, DNA_string, codons, aminoAcids);
computeORF(AA_string2, 1, DNA_string, codons, aminoAcids);
computeORF(AA_string3, 2, DNA_string, codons, aminoAcids);
system("Pause");
return 0;
}
You have some issues with your program. First of all, indexes range from 0...n-1. If you have an array of length 10, the only indexes within that range are 0...9. Essentially all of your <= operators need to become < operators (since index 9 is the 10th allocated spot in an array).
Since you are iterating in steps of three, you will need to set your upper bound lower:
for (i = 0; i <= dnaLength; i += 3)
becomes
for (i = 0; i < dnaLength - 3; i += 3)
Futhermore, you can use pointers for this assignment but that will only affect algorithm speed and will not allow dynamically allocated arrays. If you wish to change the length of a list in C++, I would recommend using std::vector.
To declare a pointer:
int *myPointer = 10;
Now myPointer is a memory address pointing to where the value 10 is stored.
&myPointer;
Will retrieve the value 10.
Additionally, regarding
(isCorrect != 0 && isCorrect != 1)
please check out this link: http://www.cplusplus.com/forum/beginner/139177/

C++: using for loop to allow user input of numbers into array

I'm new to the community and to coding as well. Right now I'm taking Intro to Computer Science at my CC and we're learning C++. Anyways, I have to create a program which asks the user for a number, which will be the size indicator of the array new_array. The program then asks the user to input the numbers one by one and afterwards, outputs them in reverse.
#include
using namespace std;
int main()
{
cout << "How many numbers?\n";
int numbers; // holds amount of numbers to be entered into array
cin >> numbers;
int new_array[numbers];
for(int counter = 0; counter < numbers; counter++)
{
cout << "Enter number " << counter << endl;
cin >> new_array[counter];
}
cout << "You entered: " << endl;
for(int i = numbers; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}
return 0;
}
I understand how to do this and for the most part, my program worked. It outputs the numbers entered in reverse just fine, but before it does so, it outputs large, strange numbers. For example, if the user enters 5 as the amount of numbers to be entered, and then enters 1, 2, 3, 4 and 6 as the 5 numbers respectively, the program outputs the number 4669476 first and then outputs the numbers in the array in reverse. Can anyone explain to me what I did wrong and how I could fix this? Thank you in advanced!
PS be gentle! I'm a newbie at this
This loop reads out of bounds:
for(int i = numbers; i >= 0 ; i-- )
{
If you follow i through in your head you will see that you output entries numbers through to 0, when in fact you should output entries numbers-1 through to 0.
An alternative patterns is:
for( int i = numbers; i--; )
Or you can use the fabled --> operator.
It would be possible to "simply" start from numbers - 1, however the loop pattern you have used would not work for an unsigned counter (because they are always >= 0). IMHO it is a good idea to use a pattern which works for all types; then you are less likely to make a mistake in future.
In your display for loop, you started from i = numbers which is out of the array's range. Since the array starts from 0 till size - 1, then you need to start from i = numbers - 1 all the way to >=0.
Because you start from array[numbers] which is not defined.
array[0], array[1], ... array[numbers-1] are defined.
In C arrays are stored from 0 instead of 1. So the last number is stored in array[4]
So when you're writing it out you should start an numbers - 1 instead of just numbers.
Because you are starting the index from out of range giving you garbage value.
your code should look some thing like this
for(int i = numbers-1; i >= 0 ; i-- )
{
cout << new_array[i] << endl;
}