我有一个包含公式名称和化合物的结构数组。我需要计算化合物的原子量。
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;
我无法将collection.formula
转换为int
值来进行实际的重量计算。我尝试使用isdigit()
检查公式中的数字以及atoi()
中的<studio.h>
以将其转换为整数。我的代码如下:
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;
}
如何转换包含数字的char
数组的部分以将其转换为int
?
The Weight Calculation of Water
错误消息是:
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 *);