Jump to content

strlen e empty strings - devolve 1


Recommended Posts

Posted (edited)

Strlen não devolve 0

Se meter o nome "a" - Strlen devolve 1

Se não meter nada (empty) Strlen devolve 1 também.

Como posso detectar emptys strings ?

 

int = 0;
    
    do {
        puts("Qual e o ID da area?");        
        fgets(buffer.idarea, MAX, stdin);
        strtok(buffer.idarea, "\n"); // Consumir o \n 
        printf("O tamanho da string que apanhei e %d\n", tam = strlen(buffer.idarea));
    } while (verifica_area_duplicadas(vector, *total, buffer.idarea) == 0); // Verificar se o ID que o utilizador inseriu já existe e se a string é empty.
Edited by thinkabout
Posted (edited)

Não estou bem a ver como resolver o problema.

Pois string com "\n" ou "a\n", devolve-me o mesmo número de caracteres.

 

Já tentei na condição ( condição 1 || buffer.idarea[0] != '\n' ), mas sem sucesso.

Edited by thinkabout
Posted
int main(void)
{
    char buffer[100];
    int tamanho;
    
    fgets(buffer,100,stdin); // Só dei enter aqui
    strtok(buffer, "\n"); 
    printf("%d\n", tamanho = strlen(buffer)); 
    
    // Output 1
    
    fgets(buffer,100,stdin); // Escrevi caracter "a"
    strtok(buffer, "\n"); 
    printf("%d\n", tamanho = strlen(buffer));
    
    // Output 1
    
    return EXIT_SUCCESS;
}
Posted

ve o que realmente estas a fazer :

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    char buffer[100];
    int tamanho;
    
    fgets(buffer,100,stdin); // Só dei enter aqui
    strtok(buffer, "\n"); 
    printf("|%s|%d\n", buffer, tamanho = strlen(buffer)); 
    
    // Output 1
    
    fgets(buffer,100,stdin); // Escrevi caracter "a"
    strtok(buffer, "\n"); 
    printf("|%s|%d\n", buffer, tamanho = strlen(buffer));
    
    // Output 1
    
    return EXIT_SUCCESS;
}

por outras palavras, strtok não serve para tirar '\n', pode ter esse efeito em alguns casos, mas como podes ver, não é a melhor solução

algo como o seguinte seria bem mais fiavel

buffer[strlen(buffer) - 1] = 0;

(isto depois de validares o resultado do fgets, claro ...)

IRC : sim, é algo que ainda existe >> #p@p
Posted (edited)
47 minutos atrás, HappyHippyHippo disse:

por outras palavras, strtok não serve para tirar '\n', pode ter esse efeito em alguns casos, mas como podes ver, não é a melhor solução

algo como o seguinte seria bem mais fiavel


buffer[strlen(buffer) - 1] = 0;

(isto depois de validares o resultado do fgets, claro ...)

 

do {
        puts("Qual e o ID da area?");
        if (fgets(buffer.idarea, sizeof (buffer.idarea), stdin) == NULL)
            break;
        buffer.idarea[strlen(buffer.idarea) - 1] = '\0'; // Limpar o /n                
    } while ( (int) strlen(buffer.idarea) == 0 || verifica_area_duplicadas(vector, *total, buffer.idarea) == 0);

Agora só tenho que ver como impeço que a minha string tenha espaços brancos no inicio e que só tenha em conta a 1 palavra de forma a não existir       "AreaC Amarela", e só existir AreaC.

Edited by thinkabout
Posted
37 minutos atrás, HappyHippyHippo disse:

sscanf

Está quase lá...

int num = 0;

 while (num == 0) {
            puts("Qual e o ID da area?");
            if (fgets(buffer.idarea, sizeof (buffer.idarea), stdin) == NULL)
                break;
            
            if (sscanf(buffer.idarea, "%s", &num) != 1) {                
                printf("string invalida\n");
                continue;
            }
        }

 

Só consigo fazer com que ele ignore uma serie espaços branco no inicio.

1º Teste - "" - Ok
2º Teste - "    "Ok
3º Teste - "     XPTO" - Aceita a string mas aceita também espaços em brancos.
4º Teste - "AreaA Verde" - Aceita as duas palavras, também não queria isto.

Posted
4 minutos atrás, HappyHippyHippo disse:

e que sucesso tiveste ?

 

A mesma coisa.

 

while (num == 0) {
            puts("Qual e o ID da area?");
            if (fgets(buffer.idarea, sizeof (buffer.idarea), stdin) == NULL)
                break;
            
            if (sscanf(buffer.idarea, " %s", &num) != 1) {    
                num = 0;
                printf("string invalida\n");
                continue;
            }
        }
Posted (edited)
20 minutos atrás, HappyHippyHippo disse:

então porque razão está como terceiro argumento do sscanf ?

int teste = 0;

    do {
        while (teste == 0) {
            puts("Qual e o ID da area?");
            if (fgets(buffer.idarea, MAX, stdin) == NULL)
                break;

            if (sscanf(buffer.idarea, " %s", buffer.idarea) != 1) {
                printf("string invalida\n");
            } else {
                // String e valida
                teste = 1;
            }
        }
        // buffer.idarea[strlen(buffer.idarea) - 1] = '\0'; // Limpar o /n       

    } while ((int) strlen(buffer.idarea) == 0 || verifica_area_duplicadas(vector, *total, buffer.idarea) == 0);

 

O sscanf remove o '\n' ? 

Mantendo esta linha estava com alguns problemas no input.

Quando fazia tipo Area1234, o que era depois inserido era Area123... 

buffer.idarea[strlen(buffer.idarea) - 1] = '\0'; // Limpar o /n    

Edited by thinkabout

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.