Character Count in C

I am trying to write a program that counts all the characters in a string. I initially received it, but then I realized that I could not count the gaps. I do not understand why this does not work.

for(m=0; z[m] != 0; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

Any help was appreciated.

Edit * Does it matter if data (rows) are scanned this way? And yes, everything is initialized. I tried to print what z [m] also evaluates, and this is not the actual value of the string in "m", I think this is the problem.

for(j=0; j<7; j++){
    printf("Enter a string:\n");
    scanf("%s", z);
        for(m=0; z[m] != 0; m++){
                if(z[m] != ' '){
                charcount ++;
                }
        }
+5
source share
4 answers

charcount. , , , z , m - int . , z[m], z[m] != 0 (! 0 = true 0 = false), . ( , , ).

, :

const char * z = "testing one two three";
int m;
int charcount;

charcount = 0;
for(m=0; z[m]; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

- String, C, , .

, ASCII. , UTF, .


: : scanf ( ). , , , z . ( scanf [ scanf], , , , , - , . : http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)

+6

strlen()

while

m = textIndex 
z = text

-

while (text[textIndex] != 0x00)
{
  textIndex++;
}
+2

scanf fgets:

char input[256];
fgets(input, sizeof(input), stdin);

fgets . , stdin , . , , , , fgets, . (''), isspace ctype.h, ( ).

, :

#include <stdio.h>
#include <ctype.h>

int count_nonspace(const char* str)
{
 int count = 0;
 while(*str)
 {
  if(!isspace(*str++))
   count++;
 }
 return count;
}

int main()
{
 char input[256];
 fgets(input, sizeof(input), stdin);
 printf("%d\n", count_nonspace(input));
}
+1

, scanf:

    scanf("%s", z);
...
                if(z[m] != ' '){

scanf ("% s" ...) always breaks in symbol space, so yours , if ever, is true . Better use fgets to read from stdin,

#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
  printf("Enter a string:\n");
  if( fgets( line, 80, stdin ) )
  {
    char *c=line;
    if( strchr(line,'\n') ) *strchr(line,'\n')=0;
    while( *c )
    {
      if( *c!=' ' )
        ++charcount;
      ++c;
    }
  }
}

Or if you want a WHITE space, take

#include <ctype.h>
...
if( !isspace(*c) )
0
source

All Articles