B
B
Borizzz2017-09-21 15:15:36
C++ / C#
Borizzz, 2017-09-21 15:15:36

How to display the result of this function?

In the example book, such a function was given, but I do not quite understand how it can output something if the while will take text indefinitely and will not end?
Tell me when the printf will work or how to write a similar function correctly?

#include <stdio.h>

int main(void) {
  int c, digic, tabs, space, next;
  while((c = getchar()) != EOF) {
    switch(c) {
      case '0' : case '1' : case '2' : case '3' : case '4' : case '5' :
      case '6' : case '7' : case '8' : case '9' : digic++;
      break;
      case ' ' : space++;
      break;
      case '\t' : tabs++;
      break;
      default : next++;
    }
  }
  printf("digic %d\n space %d\n tabs %d\n next %d\n", digic, space, tabs, next);
  return 0;
}

And help with the 2nd function, if not difficult.
Why swears at arrays?
#include <stdio.h>

int ch() {
  int c, int r[], int s[];
  int i = 0;
  while((c = getchar()) != '\n') {
    s[i] = c;
    i++;
  }
  for(int j = 0; j < i; j++) {
    if(s[i] == '\t') r[j] = "\\t";
    else r[j] = s[i];
  }
  printf("result %d\n", r[]);
}

int main(void) {
  ch();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2017-09-21
@Borizzz

EOF is a "file ended, no more data" marker. Usually getchar gives numbers from 0 to 255, and EOF is a value outside these limits (actually -1).
The console never ends, but the end of the file can be done by pressing Ctrl+Z.
Correct spelling int c; int r[]; int s[];or int c, r[], s[];. But in any case, we have a static array in front of us and we need to give it a size.
Sometimes there are arrays without a size - when we do not start the memory, but simply say: "we have some kind of memory segment in front of us." For example.

void doSmth(int a[]) {}  // передаём в функцию отрезок памяти неизвестной длины
int x[5];
doSmth(x);

extern int b[];  // компилятор рассматривает b как отрезок памяти неизвестной длины.
int b[5];    // …и только линкер подставит на место b настоящий массив

In Java, arrays are not static and are given a size when memory is allocated to them.
But this is offtopic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question