我想知道如何分割单行输入并使用malloc()为输入的每个'元素'分配内存空间而不使用
分割输入的方法如下,或者至少是最成功的方法,考虑到您希望为每个"标记"分配内存空间
#include<stdio.h>
#include <string.h>
int main() {
char string[50] = "Hello! We are learning about strtok";
// Extract the first token
char * token = strtok(string, " ");
// loop through the string to extract all other tokens
while( token != NULL ) {
printf( " %sn", token ); //printing each token
token = strtok(NULL, " ");
}
return 0;
}
和输出将是这样的:
Hello!
We
are
learning
about
strtok
您能不能试一下:
#include <stdio.h>
#include <stdlib.h>
#define MAXTOK 100 // maximum number of available tokens
int
main()
{
char str[] = "Hello! We are learning about string manipulation";
int i, j;
int len; // length of each token
char delim = ' '; // delimiter of the tokens
char *tok[MAXTOK]; // array for the tokens
int n = 0; // number of tokens
i = 0; // position in str[]
while (1) {
// increment the position until the end of string or the delimiter
for (len = 0; str[i] != ' ' && str[i] != delim; len++) {
i++;
}
// check the count of tokens
if (n >= MAXTOK) {
fprintf(stderr, "token count exceeds the array sizen");
exit(1);
}
// allocate a buffer for the new token
if (NULL == (tok[n] = malloc(len + 1))) {
fprintf(stderr, "malloc failedn");
exit(1);
}
// copy the substring
for (j = 0; j < len; j++) {
tok[n][j] = str[i - len + j];
}
tok[n][j + 1] = ' '; // terminate with the null character
n++; // increment the token counter
if (str[i] == ' ') break; // end of str[]
i++; // skip the delimiter
}
// print the tokens
for (j = 0; j < n; j++) {
printf("%sn", tok[j]);
}
}