I am trying to create a program that creates a loop to enter different values in an array.

but the program is skipping values of i. I can't understand why..

#include<stdio.h>

int main (void)
{
char s[10];
int i;
	for (i=1;i<=10;i++) {
		printf("enter %d'th value of the array 's'\n",i);
		scanf("%c",&s[i]);
		}
	printf("\n\nThe fifth value of the array is: %c", s[5]);
	fflush(stdin);
	getchar ();
	return 0;
}

EDIT .. I looked for some help on the internet and managed to do this but funnily enough the loop keeps on going and i can't understand why

#include<stdio.h>

int main (void)
{
	int i;
	char myArray [5];
	printf("\n___________Data Inputting__________________\n");
	for (i=0;i<=5;i++){
	printf("Enter value for %d:  ",i);
	scanf("%s",&myArray[i]);
   }
   printf("\n_____________________________\n");
   printf("5'th value is: %c\n\n", myArray[i]);
	fflush(stdin);
	getchar ();
	return 0;
}

Edited 5 Years Ago by terence193: added something

When you enter a value and press [Enter], the [Enter] is taken up as the next value and so it is skipped. To overcome this problem, give all the inputs in a single line separated by space (ofcourse, the prompts will be of no use then), or just append the following line of code after scanf (inside the loop):

while((c=getchar())!='\n' && c!=EOF);

Visit http://c-faq.com/stdio/scanfc.html for more details. :)

In the second code, you are using the wrong format specifier for scanning values. Use %c :)

Edited 5 Years Ago by ashlock: n/a

The program isn't skipping any values. ashlock is right, the character '\n' (Enter) is taken as a character in the input of the program. If you still want to use the functions 'scanf' and 'printf' you will have to use a "fflush(stdout)" after calling the funtion printf and a "fflush(stdin)" after calling the function scanf.

ohh, I should have thought that out. It was freaking me out and I couldn't see any visible errors in the code. Thanks @ashlock and @teo236 :]

What will exactly be done when the following code is entered
while((c=getchar())!='\n' && c!=EOF);

??

Thanks

Edited 3 Years Ago by happygeek: fixed formatting

This code actually takes the values from the input buffer until it doesn't find a '\n' or EOF.
Take this example from your code - You give 'a' as input and press [Enter]. The input buffer will contain '\n' after the value 'a' goes to the first variable. This piece of code will take the '\n' from the input buffer and put it in variable 'c', thus clearing the input buffer.

This question has already been answered. Start a new discussion instead.