0
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

char isNumber(int c)
{
    if (c >= '0' && c <= '9') {
        return 1;
    }
    return 0;
}

int main()
{
    int c;
    int prejsni = ' ';
    int stevilka = 0;
    int vsota = 0;
    char beremo = 0;
    while ((c = getchar()) != EOF) {
        if (isNumber(c) && prejsni == ' ' && beremo == 0) {
            beremo = 1;
            stevilka = c - '0';
        }else if (beremo) {
            if (isNumber(c)) {
                stevilka *= 10;
                stevilka += (c - '0');
            } else if(c == ' ' || c== '\n'){
                beremo = 0;
                // printf("%d\n", stevilka);
                vsota += stevilka;
                stevilka = 0;
            }else
            {
                beremo = 0;
                stevilka = 0;
            }
            
            
        }
        prejsni = c;
    }
    printf("%d\n", vsota);

    return 0;
}

I'm trying to read a random string and return the sum of all numbers in that string.

For example, abc123 100 a2c3 3 would return 103. When I run the program nothing happens. I simulated the execution on paper and it seems to me it should work.

For understanding: stevilka means "number", beremo means "mode if already reading a number", vsota means "sum", prejsni means "previous".

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
Tian
  • 3
  • 2
  • 3
    Btw, you could also use [isdigit](https://www.cplusplus.com/reference/cctype/isdigit/) from ctype.h. – pzaenger Jun 16 '21 at 09:45
  • Nothing happens because when all conditions are sated you just set `beremo = 1;` and then move on to check the next number. You should replace `else if (beremo)` with `if (beremo)`. – Lundin Jun 16 '21 at 09:47
  • 4
    Also make a habit of always naming your identifiers in English (I'm not native English either). Because you never know when you need someone else to take a look at your code. – Lundin Jun 16 '21 at 09:48
  • 1
    I'm assuming your question is "What can I do to find out why nothing happens in my program?", so [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – mkrieger1 Jun 16 '21 at 09:48
  • Do you input your examples interactivly from the keyboard? If so, you must explicitly signal the "end of file" with Ctrl-D (Linux) or Ctrl-Z (Windows) at the beginning of a new line. Just hitting [enter] will not return `EOF` from `getchar`. (It returns the new-line character `'\n'`.) – M Oehm Jun 16 '21 at 09:53
  • @Lundin [Is it ok to use a non-English, foreign language variable name?](https://stackoverflow.com/q/47200257/995714) – phuclv Jun 16 '21 at 10:05

0 Answers0