Originally Posted by
CS_Student8337
Thank you for the response Cas. Taking the input into a huge temporary array was originally what I was going to do but it's expressly forbidden in one of the bullets of the assignment. But I have another idea and was wondering if it would work.
Code:
if(arrayA[strlen(arrayA)] == '\n')
arrayA[strlen(arrayA)] = '\0';
if(arrayA[MAX+1] != '\n' || arrayA[MAX+1 != '\0')
while((c = fgetc(stdin)) != EOF || c != '\n');
//Assume c is declared as an int..
Basically, what I want this piece of code to do is check if the last character of the array is newline or NULL. If it's not, then it should be safe to assume that there was excess input which will be gathered one character at a time by fgetc until it reaches EOF or newline. That should clean up all of those excess characters I believe.
Please scrutinize the code. I just wrote and believe that it works except that hitting ENTER for a newline doesn't end fgets. It only ends when I use Ctrl+D.
No. You're driving me nuts here.
Info on fgets:
Code:
Syntax:
char *fgets(char *s, int n, FILE *stream);
Prototype in:
stdio.h
Remarks:
fgets reads characters from stream into the
string s.
The function stops reading when it reads
either n - 1 characters or a newline
character, whichever comes first.
fgets retains the newline character at the end
of s. A null byte is appended to s to mark the
end of the string.
Return Value:
On success, fgets returns the string pointed
to by s.
It returns null on end-of-file or error.
Example:
#include <string.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
char string[] = "This is a test";
char msg[20];
/* open a file for update */
stream = fopen("DUMMY.FIL", "w+");
/* write a string into the file */
fwrite(string, strlen(string), 1, stream);
/* seek to the start of the file */
fseek(stream, 0, SEEK_SET);
/* read a string from the file */
fgets(msg, strlen(string)+1, stream);
/* display the string */
printf("%s", msg);
fclose(stream);
return 0;
}
Let's not assume anything by checking one array element. That doesn't even sound right, does it?
I'll read thru this thread and see what's up if you promise not to Rube Goldberg it to death.
OK, you've got your sizes wrong for fgets(). You want it to be two char *LESS* than the size of the array the user is putting char's into.
So, fgets() needs space in the char array for the char's you want entered, + one space for a newline, + one space for an end of string char marker.
So adjust your number of char's you want fgets() to put into the array, accordingly. (Two char's less than the size of the array)
Then see how if that doesn't work properly for you.