问题
Simple question:
If i have a line in an input file that looks looks like:
Hello#Great#Day#Today
how can I scan in each word individually as its own array, in other words tell C to stop scanning when it reaches the # character and then go in the next iteration of the loop to scan the next word as a separate array?
回答1:
This is assuming you are reading through stdin
. Definitely take a look at @Whoz kick start approach as well (very similar to this).
What you would want to do is create a dynamic array and populate it with every byte read through stdin
. You would then want to create an array of character pointers that will point to the first character in every "word", where you define a word as every character before a '#'
character (delimiter). You would then iterate through that array of characters and populate the array of character pointers with the memory addresses of the first character in each word.
回答2:
Use strtok() to tokenize your input by the specified character.
http://www.cplusplus.com/reference/cstring/strtok/
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,"#");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "#");
}
回答3:
In two stages, I have used something like this:
#include <ansi_c.h>
//tokenizing a string
int GetCount(char *in, char *delim, int *m);
int GetStrings(char *in, char *delim, int count, char **out);
void main(void)
{
int count, maxlen, i;
char inpString[]={"Hello#Greatest#Day#Today"};
char *resultBuf[10];
//get a count of strings to store
count = GetCount(inpString, "#", &maxlen);
for(i=0;i<10;i++)
{
resultBuf[i] = calloc(maxlen+1, sizeof(char));
}
//Store strings in arrays
GetStrings(inpString, "#", count, resultBuf);
for(i=0;i<count;i++)
{
printf("%s\n", resultBuf[i]);
free(resultBuf[i];
}
}
//Gets count of tokens (delimited strings)
int GetCount(char *in, char *delim, int *m)
{
char *buf=0;
char temp1[10]={0};
char *inStr;
int count = 0;
int max = 0, keepMax = 0;
if(in)
{
inStr = calloc(strlen(in)+1, sizeof(char));
strcpy(inStr, in);
if(strlen(inStr) > 1)
{
count = 0;
buf = strtok(inStr, delim);
while(buf)
{
strcpy(temp1, buf);
max = strlen(temp1);
(max > keepMax)?(keepMax = max):(keepMax == keepMax);
count++;
buf = strtok(NULL, delim);
}
*m = keepMax;
}
free(inStr);
}
return count;
}
//Gets array of strings
int GetStrings(char *in, char *delim, int count, char **out)
{
char *buf=0;
char *inStr;
int i = 0;
if(in)
{
inStr = calloc(strlen(in)+1, sizeof(char));
strcpy(inStr, in);
if(strlen(inStr) > 1)
{
buf = strtok(inStr, delim);
while(buf)
{
strcpy(out[i], buf);
buf = strtok(NULL, delim);
i++;
}
}
free(inStr);
}
return 0;
}
来源:https://stackoverflow.com/questions/18191379/scanning-from-an-input-file-in-c-until-reaching-a-certain-character