Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fgets(), arrays, and declaring an array midway through a file

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Basically my code looks like this:

#include <stdio.h>
#include <stdlib.h>

void main(void) {
int var1, i, j, k, tempCount;
int arrayName[2];

char input1[256], input2[256];

scanf(&quot;%d&quot;, &var1);
fgets(input1, sizeof(input1), stdin);

i = 0;
j = 0;
while(input1 != '\0') {
k = 0;

while((input1 != ' ') && (input1 != '\0')) {
input2[k] = input1;
k++;
i++;
}

arrayName[j] = atoi(input2);
for(tempCount=0; tempCount<=k; tempCount++){
input2[tempCount] = ' ';
}

i++;
j++;
}
for(i=0; i<=sizeof(arrayName); i++){
printf(&quot;%d &quot;, arrayName);
}
}


It's ultimate goal is to take two lines of input, eg:

3
54 89 21

or

5
59 654 7 23 19

and put the second line as elements in an array. The first line of the input is to declare the number of items in the second line.

My code seems to skip over the fgets line, unless I remove the scanf line. Does anyone know why?

Also, it doesn't seem to be setting the first value of the second line entered into the array., the entry arrayName[0] just returns '0'. I can't see any reason for this either.

Thirdly, I wanted to declare the array &quot;arrayName&quot;, after the scanf, like this:

int arrayName[var1];

but it won't let me do that either, and again I don't know why?

Thanks in advance. :)
 
Hi,

Use the following function.

void clearStdin()
{
char cs[10];
gets(cs);
}

define this function within your program and call this function like
clearStdin();
before the the fgets and after the scanf().

These reason for this is that the scanf will store the entered integer into the variable var1 but \n character (by pressing the Enter key) will be left in the keyboard buffer(say stdin) itself.

The next fgets will take that \n and it will assume that you have given the string.

This clearStdin() just reads that \n character and clears the stdin.

Dynamic array declaration like int arrayName[var1] is not possible.

For this use dynamic memory manipulation using the malloc and free.

use like the following

int *p;
p = (int *) malloc(var1 * sizeof(int));

--Maniraja S
 
You should never use gets(), there's no way to avoid a maliscious user overflowing your buffer. Instead, try something like this:

int gobble(void)
{
int c;
while ((c=getchar())!='\n' && c!=EOF)
;
return c;
}
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top