Hi I'm a bit of a noob at c, so I was wondering why the following does not work... Code: #include <stdio.h> void end(){ int x; gets(x); exit(0); } void main(){ char c; char i; c = "Code"; gets(i); if(c==i){ printf("\r\nyes\r\n"); }else{ printf("\r\nno\r\n"); } end(); } I use windows XP. Hamish
Why do you expect it to work and what do you expect from the following program. There are lots of errors Code: gets(i); Code: c = "Code"; Code: int x; gets(x);
Really, your errors range from uninformed to eggregious. 1) main does not return void, it returns an int. Compilers that allow a void return are not standards compliant, tutorials that use it are in error. 2) Read the documentation for the funcions you use. For instance, gets: 3) c is a char. You said so in your declaration. "Code" is 5 chars. 'C', 'o', 'd', 'e', and '\0'. The latter is called a string (C string) and is indicated by double quotes rather than single quotes. A C string is an array. One cannot assign to arrays in their entirety at run time, though some compiler actions may make it seem so at compile time. Neither can C strings be compared with the "==" operator. One must use the functions declared in string.h and defined in the crt library. See other parts of this forum for recommendation on good tutorials and books. Get a good compiler. Turn on all warnings and errors. Read the documentation for functions you use. Pay particular attention to the parts about how they fail and what to do about it.
Here's one possible method. Study the functions used. Consider that there may be more secure versions for some of the functions. These are things one thinks about when one designs a solution to a problem. There are many alternatives. Design before coding, commensurate with your requirements. Code: #include <stdio.h> #include <string.h> #define MAXLEN 255 #define MAXWORDS 10 int ohHell (char *trouble) { fprintf (stderr, "%s\n", trouble); return EOF; } int main() { int count = 0; int i; char line [MAXLEN]; char words [MAXWORDS][MAXLEN]; char* newWord; printf ("Enter up to 10 words, separated by white space, on one line:\n"); if (!fgets (line, MAXLEN, stdin)) return ohHell ("Failure on input"); newWord = strtok (line, " \t\r\n"); while (newWord != NULL) { strcpy (words [count++], newWord); if (count >= 10) break; newWord = strtok (NULL, " \t\r\n"); } printf ("Contents of the array (%d items):\n", count); for (i = 0; i < count; ++i) printf ("%s\n", words [i]); return (0); }