This is a little program I'm writing to refresh my knowledge of C and I know it's wrong, but everything I've tried in order to fix it isn't working.

#include <stdio.h>
#include <string.h>
 
int main() {
  int const STR_LENGTH = 255;
  char str[STR_LENGTH];
  int n=0,i=0;
 
  printf("Please enter a word: ");
  scanf( "%s", str);
 
   for(i = 0; i < STR_LENGTH; i++){
     if(!str[i] == "\n"){ //if char does not equal newline char
        n++; //counts all characters besides newline
	printf("%c", str[i]);
     }
     else
	i = STR_LENGTH; //this will quit the for loop
   }
 
  printf("\nThe word you entered is: %s", str);
  printf("\nThe number of characters besides the newline are: %d\n", n);
  getchar();
 
  return 0;
}

scanf( "%s", str); will never include the newline into the string `str'. scanf() is designed in its default form to stop reading when it finds a space or newline.

Bottom line. scanf() is a poor choice to read input string from stdin.
fgets() is a favorite of many.

EDIT: Sorry, Aia beat me to it.

scanf( "%s", str); will never include the newline into the string `str'. scanf() is designed in its default form to stop reading when it finds a space or newline.

Bottom line. scanf() is a poor choice to read input string from stdin.
fgets() is a favorite of many.

Thanks. Since fgets() deals with files and my program only uses stdin, gets() should work fine. I'm still getting an error, warning: comparison between pointer and integer on line 13.

>Since fgets() deals with files and my program only uses stdin
stdin is an open file. scanf( "%s", str); can and should be substituted by fgets(str, sizeof str, stdin); >gets() should work fine
NO. forget that gets() exists. You can take my word for it, or you can go the long road, and search this site for a `why'.

>Since fgets() deals with files and my program only uses stdin
stdin is an open file. scanf( "%s", str); can and should be substituted by fgets(str, sizeof str, stdin); >gets() should work fine
NO. forget that gets() exists. You can take my word for it, or you can go the long road, and search this site for a `why'.

Alright. I also changed "\n" to '\n' and my comparison operator to !=. It works. Thank you.

> I also changed "\n" to '\n' and my comparison operator to !=.
That's a sensitive thing to do, since "\n" is a string made of '\n' and '\0'.

That's a sensitive thing to do

But the correct thing to do, as "\n" is a pointer, not a char. Comparison between a char and a pointer to a char cannot be expected to work properly (who knows what "properly" even means here?)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.