mateus_7 2 Denunciar post Postado Maio 4, 2014 oi pessoal, eu estava dando uma olhada aqui -> http://www.cplusplus.com/reference/cstdio/scanf/ <-e surgiu uma duvida... Pelo que eu entendi, o retorno de scanf() é o valor de variaveis** lidas** com sucesso(certo ou nao?).Aí eu tentei fazer: Colocar numa variavel o valor de retorno... Aí quando a 1° letra digitada é invalida o programa trava (nao sei por que). E quando por exemplo digito -> cafe e bom9aqui ja nao aparece <-Mas ele sai do laco, e na variavel fica cafe e bomTem alguma forma de repetir o scanf() novamente se por exemplo o usuario errar na metade?No site acima também estava escrito:"Any number of the characters specified between the brackets.A dash (-) that is not the first character may produce non-portable behavior in some library implementations."isso quer dizer que usar scanf("%[a-z A-Z]s",variavel) é non-portable por causa do '-'? ou qual é a situacao que o '-' "atrapalha"? #include <stdio.h> #include <stdlib.h> int main(void) { char nome[100]= {}; int i=1; printf("Digite o nome: "); do { i=scanf("%[A-Za-z ]s",nome); } while(i==0); printf("\n\no nome e: %s",nome); return 0; } Compartilhar este post Link para o post Compartilhar em outros sites
_Isis_ 202 Denunciar post Postado Maio 4, 2014 Vou colar o texto da manpage porque talvez esteja um pouco mais claro: RETURN VALUE Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned, and errno shall be set to indicate the error. Digitei "9" como entrada para o programa que vc escreveu. Examinando a variável errno (precisa incluir errno.h), a mensagem impressa é "Success". O scanset fez o serviço, mas devido à condição i==0 do loop, ele fica preso no while (9 não é aceito e \n também não é aceito, o que faz o scanf retornar 0). Fazer o scanf retornar caso o usuário digite algo inválido (ex: %[0123456789]s e a entrada contém números e letras) é algo bem difícil, pois o scanset filtra os dados no buffer do stdin. Usando o scanset dado como exemplo, se eu informar 62d8, a variável receberá 62 e strerror(errno) imprimirá "Success". Apenas quando o primeiro caractere for incorreto (de acordo com o scanset) é que será possível detectar o erro na entrada de dados. If a '-' is in the scanlist and is not the first character, nor the second where the first character is a '^', nor the last character, the behavior is implementation-defined. Atenção aqui: o comportamento não é indefinido, fica a critério do implementador do compilador/linguagem e deve estar documentada. No caso do meu ambiente, funciona como uma expressão regular: ao invés de eu ter que digitar todo o alfabeto em minúsculas, ele funciona como um operador de intervalo. Devido ao padrão da linguagem deixar a cargo do implementador, ele tem problemas de portabilidade nos demais casos não listados no padrão. http://stackoverflow.com/questions/18420753/unspecified-undefined-and-implementation-defined-behavior-wiki-for-c http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior P/ ler dados recomenda-se utilizar o fgets. Compartilhar este post Link para o post Compartilhar em outros sites
mateus_7 2 Denunciar post Postado Maio 4, 2014 "If a '-' is in the scanlist and is not the first character, nor the second where the first character is a '^', nor the last character, the behavior is implementation-defined." E mais simples. vlw Compartilhar este post Link para o post Compartilhar em outros sites