The simplest solution would be to use the % c library function, which allows you to read word by word based on a separator.
My answer is in everything similar to the one in the documentation except that I created an array of strings to store the various values found.
It would obviously be impractical to store the various values in single variables.
Code:
int i = 0;
char str[1000];
scanf("%[^\n]s", str);
//primeiro achar a quantidade de separadores para criar o array com o tamanho certo
char *letra = str;
int separadores = 0;
while (*letra != 'palavra = strtok(NULL, ";");
'){
if (*(letra++) == ';') separadores++;
}
char* palavras[separadores]; //criar o array de palavras interpretadas
char *palavra = strtok(str, ";"); //achar a primeira palavra com strtok
while (palavra != NULL){ //se já chegou ao fim devolve NULL
palavras[i++] = palavra; //guardar a palavra corrente e avançar
palavra = strtok(NULL, ";"); //achar a próxima palavra
}
Notice the private call that is made to find the second and subsequent words:
char str[1000];
char strOriginal[1000];
strcpy(strOriginal, str); //copiar de str para strOriginal
//resto do código
You get the value strtok
. This causes NULL
to continue in the last search word, as indicated in the documentation:
Alternativelly, a null pointer may be specified, in which case the
function continues scanning a previous successful call to the
function ended.
It is also important to indicate that strtok
changes the original string, so if you need to use it later in the code you should make a copy of it before finding the words. The most suitable function for this would be strtok
:
int i = 0;
char str[1000];
scanf("%[^\n]s", str);
//primeiro achar a quantidade de separadores para criar o array com o tamanho certo
char *letra = str;
int separadores = 0;
while (*letra != 'palavra = strtok(NULL, ";");
'){
if (*(letra++) == ';') separadores++;
}
char* palavras[separadores]; //criar o array de palavras interpretadas
char *palavra = strtok(str, ";"); //achar a primeira palavra com strtok
while (palavra != NULL){ //se já chegou ao fim devolve NULL
palavras[i++] = palavra; //guardar a palavra corrente e avançar
palavra = strtok(NULL, ";"); //achar a próxima palavra
}
Example working on Ideone