A
A
Anton Frolov2016-02-29 17:22:51
C++ / C#
Anton Frolov, 2016-02-29 17:22:51

Why does else always work?

#include <stdio.h>
#include <ctype.h>
int alph(int ch);
int main(void) {
    int ch;
    
    while ((ch = getchar()) != EOF) {
        if (isalpha(ch)) {
            putchar('"');
            putchar(ch);
            putchar('"');
            printf(" является буквой!\n"
                   "Ее номер: %d\n", alph(ch));
        }
        else {
            //printf("%d", alph(ch));
            printf("2\n");
        }
    }
    return 0;
}
int alph(int ch) {
    if (!isalpha(ch))
        ch = 'a';
    return ch - 96;
}

A program that asks for input and checks whether it is a letter, if yes, then displays the number of this letter, if not, then it should output 2, but for some reason it displays two two times in a row, also if it is a letter, the else operator still fires, which leads to the appearance of an extra two. The program is simple, but I don’t understand what the problem is, I’m sure that everything is extremely simple ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2016-02-29
@TonyMaster

Everything works correctly. It's just that after you enter a letter, you still have the first line captured by
C:\MinGW\bin>test.exe
a
"a" is a letter!
Her number is: 1
[10]
1
[49]
[10]
3
[51]
[10]
a
"a" is a letter!
Her number: 1
[10]
b
"b" is a letter!
Her number: 2
[10]

#include <stdio.h>
#include <ctype.h>
int main(void) {
    int ch;
    
    while ((ch = getchar()) != EOF) {
  if (ch=='\n' || ch=='\r') continue;
        if (isalpha(ch)) {
            printf("[%c] является буквой, ее номер: %d\n", ch, ch-96);
        }
        else {
            printf("[%d] это не буква\n", ch);
        }
    }
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question