【发布时间】:2017-05-03 04:28:38
【问题描述】:
这是my last question的延续。
到目前为止,我已成功获取用户输入并将其存储到字符串中。比如我转了这个:
1:E 2:B 2:B 2:B 4:G
进入这个:
1:E2:B2:B2:B4:G
这是一个字符串数组。
这是我接下来想做的,但它不适合我:
1E2B2B2B4G
其中每一个都是存储在字符数组中的字符。
这是我正确运行的代码块:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_INPUT_SIZE ( (sizeof(char)*96) + (sizeof(int)*48) )
int main () {
char *input = malloc(MAX_INPUT_SIZE);
printf("Example input: 1:E 2:C 2:C 2:C 8:D\n");
printf("Your input:\n\n");
fgets(input, MAX_INPUT_SIZE, stdin);
// Removing newline
if ( (strlen(input) > 0) && (input[strlen(input) - 1] == '\n') )
input[strlen(input) - 1] = '\0';
int i = 0;
char *p = strtok(input, " ");
char *array[MAX_PAIRS];
while (p != NULL){
array[i++] = p;
p = strtok(NULL, " ");
}
// Checking the array
int j = 0;
for (j=0; j<i; j++) {
printf("\n %s", array[j]);
}
这段代码运行良好。接下来是我目前正在使用的代码:
int k = 0;
int l = 0;
char *letter = malloc( sizeof(char) * (i * 2) );
for (k=0; k<i; k++) {
char *q = strtok(array[k], ":");
while (q != NULL) {
letter[l++] = q;
q = strtok(NULL, ":");
}
}
// Checking the array
int m = 0;
for (m=0; m<l; m++) {
printf("\n %c", letter[m]);
}
return 0;
}
当我去检查数组时,它会为我想要打印的每个字符打印一个垃圾符号。我不明白我在这里做错了什么。
【问题讨论】:
-
letter[l++] = q;-->letter[l++] = *q; -
@BLUEPIXY 非常感谢。正如我在下面的答案中提到的那样,仍然不确定其背后的逻辑是如何工作的,但现在我的代码可以正常工作,所以我很高兴。
-
*q是指针指向的字符。