I'm trying to make a simple C program that scans an array of chars to see if its elements are similar.
I can't understand what's wrong. Could you help me to fix this? Here is the code.
Thanks!
#include<stdio.h>
int main() {
int arr[10];
int i, len;
int flag = 0;
printf("Enter a word: ");
for (i = 0; i < 10; i++)
scanf("%d", &arr);
len = sizeof(arr);
for (i = 0; i < len - 1; i++) {
if (arr != arr[i + 1])
flag = 1;
}
if (flag == 0)
printf("The array has different elements.");
else
printf("The array has similar elements");
return 0;
}
#include <stdio.h>
int main(void) {
int arr[10];
int i, x, len;
int flag = 0;
printf("Enter a word: ");
for (i = 0; i < 10; i++) {
scanf("%d", &x);
arr=x;
}
// len = sizeof(arr);
len = (int)( sizeof(arr) / sizeof(arr[0]) );
for (i = 0; i < len - 1; i++) {
if (arr != arr[i + 1]) {
flag = 1;
}
}
if (flag == 1) {
printf("The array has different elements.");
} else {
printf("The array has similar elements");
}
return 0;
}
akshay@Aix:/tmp$ cat tmp.c
#include <stdio.h>
#define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
void main() {
int i, x, arr[10];
printf("Enter a word: ");
for (i = 0; i < 10; i++) {
scanf("%d", &x);
arr=x;
}
for (i = 0; i < N_ELEMENTS(arr); i++) { printf("%d\n",arr);
if (arr != arr[i + 1]) {
printf("The array has different elements\n");
return ;
}
}
printf("The array has similar elements\n");
}
akshay@Aix:/tmp$ gcc tmp.c
akshay@Aix:/tmp$ ./a.out
Enter a word: 1 1 1 1 1 1 1 1 1 1
1
1
1
1
1
1
1
1
1
1
The array has similar elements
akshay@Aix:/tmp$ ./a.out
Enter a word: 1 2 3 4 5 6 7 8 9 10
1
The array has different elements
The first time you run it, it sees a number and scans it.
The second time you run it, it hits whitespace of some sort -- a space or newline. This is not a digit, so it gives up.
The third time you run it, it hits the same whitespace. It's going to just keep slamming its head into the wall over and over again.
In summary, don't use scanf, it's a royal pain. Read lines yourself, tokenize them yourself, then use sscanf if you must. It will never pull this trick on you.
char buf[512];
int arr[10];
while(fgets(buf, 512, stdin))
{
int n=0;
char *tok=strtok(buf, " \r\n\t"); // Split on any whitespace, including newlines (which fgets includes).
while(tok != NULL)
{
if(sscanf(tok, "%d", arr+n) != 0)
{
n++;
tok=strtok(NULL, " \r\n\t"); // Keep splitting on the last string we gave it until done.
continue;
}
break;
}
printf("scanned %d numbers\n", n);
}