Converting parts of char array to Int array for calculations - c++

I have an array of structs which contains Formula Name, and Chemical Compound. I need to calculate atomic weight of compound.
struct compounds{
char name[20]; // Dihydrogen Monoxide (Water)
char formula[30]; //H2O
};
const int SIZE = 100;
compounds collection[SIZE];
int formula_1[30];
int k;
I have trouble converting collection.formula to int values to do the actual weight calculations. I trying to use isdigit() to check for numbers in the formula and atoi() from <studio.h> to convert them to integers. My code is as follows:
for (int i=0; i<SIZE; i++){
infile >> collection[i].name >> collection[i].formula;
//cout << collection[i].name << " " << collection[i].formula << endl;
//Convertion CHAR to INT
for(int j=0; j<30; j++){
if(isdigit(collection[i].formula[j])){
k = atoi (collection[i].formula[j]);
}
}
}
//Store in array of INT
for (int m=0; m<30; m++){
formula_1[m] = k;
}
What can be done to convert parts of char array containing numbers to convert them to int?
The Weight Calculation of Water
The error message is:
midterm_q2.cpp: In function 'int main()':
midterm_q2.cpp:40:39: error: invalid conversion from 'char' to 'const char*' [-fpermissive]
k = atoi (collection[i].formula[j]);
^
In file included from midterm_q2.cpp:3:0:
c:\mingw\include\stdlib.h:335:38: note: initializing argument 1 of 'int atoi(const char*)'
_CRTIMP __cdecl __MINGW_NOTHROW int atoi (const char *);

Related

How Should i pass An 2d Array To an Function in c++ using pointers [duplicate]

This question already has answers here:
Passing a 2D array to a C++ function
(17 answers)
Closed 2 years ago.
I am not able to pass 2D array in C++ initialized by main function to addMatrix function.
ERROR MESSAGE
Main.cpp: In function 'int main()': Main.cpp:15:23: error: cannot convert 'int ()[(((sizetype)(((ssizetype)c) + -1)) + 1)]' to 'int' for
argument '1' to 'void addMatrix(int, int*, int, int)'
addMatrix(a,b,r,c);
void addMatrix(int**, int**, int, int);
int main()
{
int r, c, i, j;
cin >> r >> c;
int a[r][c], b[r][c];
// ASSUME HAVE TAKEN INPUTS FROM BOTH THE MATRIX A AND B
addMatrix(a, b, r, c);
}
void addMatrix(int** a, int** b, int r, int c)
{
int i, j, d[r][c];
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
d[i][j] = a[i][j] + b[i][j];
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
cout << d[i][j] << " ";
cout << endl;
}
}
These declared arrays
int a[r][c],b[r][c];
used in expressions like for example function arguments are implicitly converted to pointers to their first elements of the type int ( * )[c].
However the corresponding function parameters have the type int **.
void addMatrix(int **,int **,int,int);
So the compiler issues an error because these types are not compatible.
Pay attention to that variable length arrays is not a standard C++ feature.
Use instead objects of the class template std::vector.
If your compiler supports variable length arrays then the function should be declared like
void addMatrix( int, int, int [][*], int [][*] );
Or if the declaration is at the same time the function definition then
void addMatrix( int r, int c, int [][c], int [][c] );
or (for self-documenting)
void addMatrix( int r, int c, int [r][c], int [r][c] );

Need help passing an array of structure to a function

So, I am currently studying at school and I need to do my homework. I am a beginner in C++ and somehow the compiler shows me an error in my code. Basically, I have a .txt file where the data is stored.
The .txt file looks something like this:
5
Petras 23.25 10.50
Rimas 125.40 1.20
Romas 55.00 1.00
Jurgis 1000.90 0.25
Algis 15.00 25.50
The first line shows how much people in the list we have, so I created integer n.
Next we have a list of people. The list tells the name of the person, how much money he has in different currency, and shows the rate of exchange to euros.
And the problem is that I am trying to find the sum of the money they have in Euros. This is my code.
#define USE_MATH_DEFINES
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
const int Cn = 100;
const int Cname = 15;
int n;
struct listofpeople {
string name;
double MoneyInOtherCurrency;
double RateOfExchange;
double MoneyInEuros;
};
listofpeople A[Cn + 1];
void data();
void ChangeCurrency();
double sum(double C[], int m);
int main () {
data();
ChangeCurrency();
cout << sum(A[].MoneyInEuros, n);
return 0;
}
//-------------------------------------------------------
void data(){
ifstream is ("U2duom.txt");
is >> n;
char symbols[Cname + 1];
for(int i = 1; i <= n; i++){
is.ignore(80, '\n');
is.get(symbols, Cname);
A[i].name = symbols;
is >> A[i].MoneyInOtherCurrency;
is >> A[i].RateOfExchange;
}
}
//----------------------------------------------------------
void ChangeCurrency(){
for(int i = 1; i <= n; i++){
A[i].MoneyInEuros = A[i].MoneyInOtherCurrency*A[i].RateOfExchange;
cout << A[i].name << " " << A[i].MoneyInEuros << " " <<
A[i].MoneyInOtherCurrency << " " << A[i].RateOfExchange << endl;
}
}
//---------------------------------------------------------------
double sum(double C[], int m){
double a = 0;
for(int i = 1; i <= m; i++){
a= a + C[i];
}
return a;
}
And the problem is that the compiler shows me an error in the line where i try to print the sum. Could anyone help me? Thanks.
EDIT:
My compiler shows this error:
error: expected primary-expression before ']' token
If I specify array elements I want to use, for example:
sum(A[n].MoneyInEuros, n);
The compiler shows this error:
cannot convert 'double' to 'double*' for argument '1' to 'double
sum(double*, int)'
double sum(double C[], int m); takes an array of doubles, but you only have an array of listofpeople. This doesn't work.
You have to change sum so that it takes an array of listofpeople, or you change your data structure from a Structure Of Arrays to an Array of Structures (better for performance, more complex to handle).
Typically, sum requires reimplementing:
double sum(listofpeople *s, int m);
Be aware that in C++, we don't use the [] notation for types.

Trying to convert an char to integer

So i'm trying to produce the sum of the variable date of type char in the following code using the atoi() function. But when doing so it returns this error message: test.cpp:9:25: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] and i can't seem to figure out what the problem is, help would be greatly appriciated.
#include <iostream>
using namespace std;
int calcNumber(const char* date, const int arraySize)
{
int sum(0);
for (int count=0; count<arraySize; count++) {
sum += atoi(date[count]);
}
return sum;
}
int main()
{
char date[] = "131083";
cout << calcNumber(date, sizeof(date) / sizeof(date[0]));
}
The std::atoi function expects a const char* type. When dereferencing a pointer of type const char* with the [] operator you are supplying the char type. That being said what you need there is the std::strlen function to determine the length of your character array -1 to address the \0 null terminating character and your count <= arraySize condition:
#include <iostream>
int calcNumber(const char* date, const size_t arraySize) {
int sum = 0;
for (int count = 0; count <= arraySize; count++) {
sum += date[count] - '0';
}
return sum;
}
int main() {
const char* p = "1234";
std::cout << calcNumber(p, strlen(p) - 1);
}
date[count] is a single char, perhaps '3' (that is ASCII code 51, so it is the same as (char)51).
To convert that into a small number (e.g. 3), use date[count]-'0'
(of course '0' is also a char constant literal, its value is 48 in ASCII; and the ASCII encoding is such that digits glyphs are encoded by consecutive codes).
BTW, you want to stop on a zero byte (terminating every string). So you could use
for (int count=0; date[count] != (char)0; count++) {
sum += atoi(date[count]);
}
then you don't even need to pass any arraySize.
Actually, you are re-inventing (poorly) std::atoi (or strtol). Your calcNumber would handle incorrectly strings like "2X" (but std::atoi("2X") gives 2 which makes more sense). And your calcNumber also behaves badly on "-34" or on " 1"....

Error: invalid conversion from int to int(*)[4] in function calls

I'm working on a homework project where I have to do a modified preorder traversal through an array-based tree and I need to pass the array to the function in order to use it but I keep getting an error in the function saying that it's an invalid conversion from int to int(*)[4] and I can't seem to figure out why.
Here's a copy of my code:
#include <iostream>
#include <fstream>
char code[10];
void preOrder(int tree[][4], int index, int treeDepth)
{
int tempIndex;
if(tree[index][2] == -1 && tree[index][3] == -1)
{
std::cout << char(tree[index][1]) << ": ";
for(int i = 0; i < treeDepth; i++)
std::cout << code[i];
std::cout << "\n"
}
else
{
for(int i = 0; i < 2; i++)
{
code[treeDepth] = 0;
tempIndex = tree[index][2];
preOrder(tree[index][2], tempIndex, treeDepth + 1);
code[treeDepth] = 1;
tempIndex = tree[index][2];
preOrder(tree[index][3], tempIndex, treeDepth + 1);
}
}
return;
}
int main()
{
int numNodes = 0, i = 0, j = 0;
int root = 0, treeDepth = 0;
int numcols = 4;
std::fstream inFile;
inFile.open("tree.dat");
inFile >> root;
inFile >> numNodes;
int huffmanTree[numNodes][numCols];
for(i = 0; i < numNodes; i++)
for(j = 0; j < numCols; j++)
inFile >> huffmanTree[i][j];
preOrder(huffmanTree, root, treeDepth);
inFile.close();
return 0;
}
Any help would be greatly appreciated.
And also I can't use pointers and I can also declare huffmanTree as global but couldn't figure out how to get that to work either. And also sorry for the way everything it placed. This is my first time posting.
The errors are:
ola.cpp: In function ‘void preOrder(int (*)[4], int, int)’:
ola.cpp:28:53: error: invalid conversion from ‘int’ to ‘int (*)[4]’ [-fpermissive]
ola.cpp:10:6: error: initializing argument 1 of ‘void preOrder(int (*)[4], int, int)’ [-fpermissive]
ola.cpp:31:53: error: invalid conversion from ‘int’ to ‘int (*)[4]’ [-fpermissive]
ola.cpp:10:6: error: initializing argument 1 of ‘void preOrder(int (*)[4], int, int)’ [-fpermissive]
ola.cpp: In function ‘int main()’:
ola.cpp:67:39: error: cannot convert ‘int (*)[(((sizetype)(((ssizetype)numCols) + -1)) + 1)]’ to ‘int (*)[4]’ for argument ‘1’ to ‘void preOrder(int (*)[4], int, int)’
Regarding your error on line 67: in Standard C++ this is not permitted:
int huffmanTree[numNodes][numCols];
Only constant expressions may be used as array dimensions.
Some compilers implement a non-standard extension to allow this sort of array, but not very well: it appears that, for your compiler, this extension doesn't extend to passing the array to a function that expects an array of fixed width.
Possibly it would fix your problem to use const int numcols = 4; instead.
The errors on line 28 and 31 are due to calling preOrder(tree[index][2] . Your first argument is an int but the function expects pointer to array. If you're trying to create a slice of the array starting at some particular row and column - that actually isn't possible. You'd have to pass tree, index, 2, tempIndex, treeDepth + 1 instead, adding 2 more parameters to your function which indicate the starting point; and modifying the function logic accordingly.

invalid conversion from 'int' to int* [-fpermissive]

Previously I had this implemented and it worked:
int *train_X = (int *)mxGetData(IN_a);// pointer to 6th argument matrix train_X
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
cout << train_X[6 * i + j] << endl;
}
}
int sizeTrain_X1 = mxGetM(IN_a);
int sizeTrain_X2 = mxGetN(IN_a);
I could even manage to check if i get the correct sizes with the following and it was all good.
cout <<"Training input NumOfCollum:\n"<< sizeTrain_X1 << endl;
cout << "Training input NumOfRows:\n"<<sizeTrain_X2 << endl;
but then when trying my entire program with the following initialization i get a compilation error:
for (int epoch = 0; epoch<training_epochs; epoch++)
{
for (int i = 0; i<train_S; i++)
{
rbm.contrastive_divergence(train_X[i], learning_rate, k);
}
}
Here is the error message:
RBM.cpp: In function ‘void mexFunction(int, mxArray**, int, const
mxArray**)’:
RBM.cpp:570:64: error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
RBM.cpp:81:6: error: initializing argument 1 of ‘void RBM::contrastive_divergence(int*, double, int)’ [-fpermissive]
RBM.cpp:615:32: error: invalid types ‘int[int]’ for array subscript
train_X is an int*. When you do train_X[i] you now get an int. contrastive_divergence() though wants an int*. Since you cannot convert an int to an int* you are getting the subsequent error. You either need to pass the address of train_X[i] as &train_X[i] or just pass train_X