C novice programmer - please explain this error

I'm just starting with C and looking for some examples from Richieโ€™s book. I wrote a small program for understanding arrays of characters, but came across some errors and hoped for some understanding of what I misunderstood:

#include <stdio.h> #define ARRAYSIZE 50 #include <string.h> main () { int c,i; char letter[ARRAYSIZE]; i=0; while ((c=getchar()) != EOF ) { letter[i]=c; i++; } letter[i]='\0'; printf("You entered %d characters\n",i); printf("The word is "); printf("%s\n",letter); printf("The length of string is %d",strlen(letter)); printf("Splitting the string into chars..\n"); int j=0; for (j=0;j++;(j<=strlen(letter))) printf("The letter is %d\n",letter[j]); } 

Conclusion:

 $ ./a.out hello how are youYou entered 17 characters The word is hello how are you The length of string is 17Splitting the string into chars.. 

What's happening? Why doesn't the for loop output?

+6
source share
5 answers

The syntax should be:

 for (j=0; j<strlen(letter); j++) 

Since strlen is an expensive operation, and you do not change the line inside the loop, it is better to write like this:

 const int len = strlen(letter); for (j=0; j<=len; j++) 

In addition, it is strongly recommended that you always check for buffer overflows when working with C-lines and user input:

 while ((c=getchar()) != EOF && i < ARRAYSIZE - 1) 
+11
source

Error in for, just replace the end condition and the increment as follows:

 for (j = 0; j <= strlen(letter); j++) 

Question: what is the last character?

+7
source

for (j=0;j++;(j<=strlen(letter))) This is not true.

It should be for (j=0; j<=strlen(letter); j++) - an increment in the third position.

+4
source

The correct for loop format is:

 for (initialization_expression; loop_condition; increment_expression){ // statements } 

so your for loop should be

 for (j = 0; j < strlen(letter); j++) 
+3
source

In the for loop, the condition is i ++, which for the first time evaluates to false (0). You need to change them: for (j=0; j <= strlen(letter); j++)

+2
source

Source: https://habr.com/ru/post/915307/


All Articles