The simplest solution would be even using the function strtok
of the library of c, which lets you read word by word based on a tab.
My answer is all the same as in the documentation except that I created an array of strings to store the various values found.
It would obviously be impossible to store the various values in loose 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 != '\0'){
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
}
Note in the particular call that is made to find the second and subsequent words:
palavra = strtok(NULL, ";");
Who gets the value NULL
. This causes the strtok
continue in the last word that had been searched, as indicated in the documentation:
Alternatively, a null Pointer may be specified, in which case the
Function continues Scanning Where a Previous Successful call to the
Function ended.
It is also relevant to indicate that the 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 the strcpy
:
char str[1000];
char strOriginal[1000];
strcpy(strOriginal, str); //copiar de str para strOriginal
//resto do código
Example working on Ideone
If you are interested in maintaining the original state of
str
, just make a copy usingstrcpy
for another variable and usestr
to tokenize.– Jefferson Quesado
@Jeffersonquesado Yes I did not talk about it but yes it is relevant to indicate that the
strtok
actually changes the original string. Thank you for reminding– Isac
some college trauma that I wish other people wouldn’t go through :) After all, it’s not everyone who remembers RTFM.
– Jefferson Quesado
@Jeffersonquesado I fully agree. The c is full of little details that end up giving you headaches and time consuming when you don’t know about them.
– Isac