-
help with my overfollow
I cant get this code to stop allowing overfollow on the inputs. at the moment it carries any char's over 7 on to the next line and messes it up.
is there a way i can stop this?
Code:
#include <stdio.h>
int main()
{
char a[10];
char b[10];
char out[20];
printf( "Please enter a Maximum of 7 whole numbers: " );
fgets( a, sizeof a, stdin );
printf( "Enter your last name: " );
fgets( b, sizeof b, stdin );
printf( "\nString 'a' %s \n", a);
printf( "\nString 'b' %s \n", b);
if (a[0] == b [0])
out[0] = a[0];
else {
out[0] = 45;
}
if (a[1] == b [1])
out[1] = a[1];
else {
out[1] = 45;
}
if (a[2] == b[2])
out[2] = a[2];
else {
out[2] = 45;
}
if (a[3] == b [3])
out[3] = a[3];
else {
out[3] = 45;
}
if (a[4] == b[4])
out[4] = a[4];
else {
out[4] = 45;
}
if (a[5] == b[5])
out[5] = a[5];
else {
out[5] = 45;
}
if (a[6] == b[6])
out[6] = a[6];
else {
out[6] = 45;
}
if (a[7] == b[7])
out[7] = a[7];
else {
out[7] = 45;
}
//out[8] ='\0';
printf( "\nThe intersection is %s \n", out);
getchar();
return 0;
}
-
You may want to consider a slightly bigger string size than 10 - 7 digits + cr + lf + 0 = 10 digits, anything more will go to the next memory location after your intended ones.
If you strictly want to read 7 digits on one line, and you want to ensure that the next read starts at the next line, I think you'll need to write your own little input loop that reads a fixed number of characters, then skips until it reaches "end of line" ('\n'). Take care to consider end of file too - someone may want to feed your program from a file, and may not have a correct format, you don't want your program to hang in that situation.
--
Mats
-
After just a quick look, you could read in more characters (say up to 20) and then only use the first 7.
-
I couldnt get what you are trying to do? It may be my fault , but what is the aim?
-
While using fgets, one way to know if what the user entered had more characters than what you could store in your variable is to check if the newline character appears in your char array. If it doesn't, then you "purge" the input buffer, else you do nothing. This is an example:
Code:
#include <stdio.h>
#include <string.h>
#define FPURGE() while(getchar() != '\n')
int main()
{
char buffer[50];
printf("Enter something: ");
fgets(buffer, sizeof(buffer), stdin);
if (buffer[strlen(buffer) - 1] == '\n')
{
// You could remove the '\n' from the string if you want here
// but this isn't what i want to show anyway
}
else
{
// User entered something with more thant sizeof(buffer) characters
FPURGE();
}
// ...
return 0;
}
-
ROFL!
I suggest you skip ahead to learning for-loops, and then come back and fix this.