Pergunta

I am messing around with the function below, I want to end input capture when user enters a DOT character. It seems that getche() is not doing what it is intentended to do:

void Encode(FILE *fp)
{
    char chWord[100]; 
    char *chP;

    printf("Enter a word or a sentence, close it by a \".\"\r\n");
    scanf("%s",chWord);

    if (chWord != '.')
    {
        for (chP = chWord; *chP != '\0'; chP++) //to print each digit till end of string \0
        {
            printf("%d ",*chP+10);
            fprintf(fp, "%d ",*chP+10);     
        }
    }
}

UPDATE

It seems that I was not clear enough. What I am trying to do is when user enters a DOT it should act like pressing ENTER key so the program goes to next step. Some sort of simulating ENTER key.

Foi útil?

Solução 3

OK, backing out that whole Answer based on your update...

The answer is no, there is no way to do what you want to do with scanf, or anything in standard C for that matter. What you're trying to do is platform (and possibly compiler) specific.

If you want to treat the '.' as a enter key press you have to do the magic yourself. So, since you didn't mention if you were using any specific OS or compiler I'll give you the first example that comes to mind.

This works with Windows MS VS:

#include <Windows.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char key = 0;
    int counter = 0;
    char chWord[100] = {0};
    while(counter < 100) {
       while(!_kbhit()) {    //While no key has been hit
           Sleep(1);         //Sleep for 1 ms
       }
       key = _getch();       //Get the value of the key that was hit
       if(key == '.')        //if it was a .
         break;              //act as if it were an "enter" key and leave
       else
         chWord[counter] = key;
       counter++;
    }
    chWord[99] = '\0';
    printf("The string was %s\n", chWord);
    return 0;
}

Outras dicas

 if (chWord != '.')

should be

 if (*chWord != '.')

you are comparing a char pointer to a char instead of a char to another char.

be aware that the way this code is written the input ".123" will skip the printing segment. not sure if this is desireable to you or not.

The scanf family of function accept a (negative)character set as a format specifier.

You can do scanf("%[abc]", chWord); to accept only strings composed of the letters abc.

And you can also specify which characters not to accept. So scanf ("%[^.]", chWord); will accept a string composed of anything but a dot.

Edit

I forgot to mention, that the dot will remain in the input stream buffer, so to read and ignore it during the scanf itself (rather than flush the buffer or do a getchar), just add it to the end of the format string. I.e.:

scanf ("%[^.].", chWord);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top