我试图将字符串S作为输入。这里字符串S可以包含多个整数值,后跟一个字母表。该程序必须根据先前的整数值扩展字母表。如何从字符串中读取多个数字号码
考虑输入:4a5h
的量,输出:aaaahhhhh
,即4倍a
倍和5倍h
同样对于输入:10a2b
输出:aaaaaaaaaabb
,即10倍a
和2倍b
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char s[1000], alp[1000];
int num[1000];
int n = 0;
int i, j, k, m;
k = 0;
scanf("%[^\n]s", s);//Reads string until newline character is encountered
for (i = 0; i < strlen(s); i++) {
if (isalpha(s[i])) {
alp[n] = s[i]; // alp[] stores the alphabets
n += 1;
} else {
num[k] = s[i] - '0';// num[] stores the numbers
k += 1;
}
}
for (i = 0; i < k; i++) {
for (m = 0; m < num[i]; m++)
printf("%c", alp[i]);
}
return 0;
}
但是,通过此代码,我无法读取2或3或N位数字。因此,如果输入是100q1z
那么alp[]
阵列很好,但num[]
阵列不包含100
和1
,因为它的元素代替1
和0
是它的元素。
如何纠正这种代码?
1)'k'应'0'作为初始值。 – BLUEPIXY
感谢那@BLUEPIXY –