nathanqh
October 12th, 2008, 05:38 PM
Hello there. I'm written the following code in C and in theory I want rank[] to store a char and an int. When I run the program though, this is what I get:
Employee: hello
Employee number: 1234
hello1234
hello1234
add another (y/n)?
y
Employee: asdfg
Employee number: 5678
asdfg1234
asdfg5678
add another (y/n)?
instead of printing
asdfg1234
asdfg5678
shouldn't it output
hello1234
asdfg5678 ?
I'm just wondering why I'm getting asdfg instead of hello? Thanks!
#include <stdio.h>
#include <stdlib.h>
typedef struct {
const char *emp;
int num;
} InfoT;
int main () {
char* employee;
int number;
InfoT rank[20];
int size = 0;
if((employee = calloc(21, sizeof(char))) == NULL) {
return EXIT_FAILURE;
}
while(1) {
printf("Employee: ");
while (1) {
if (scanf("%s", employee) != 0)
break;
getchar();
}
printf("Employee number: ");
while (1) {
if (scanf("%d", &number) != 0)
break;
getchar();
}
rank[size].emp = employee;
rank[size].num = number;
printf("%s%d\n", rank[0].emp, rank[0].num);
printf("%s%d\n", rank[size].emp, rank[size].num);
printf("add another (y/n)?\n");
while (getchar() != '\n')
;
if (getchar() == 'n')
break;
size++;
}
return EXIT_SUCCESS;
}
Employee: hello
Employee number: 1234
hello1234
hello1234
add another (y/n)?
y
Employee: asdfg
Employee number: 5678
asdfg1234
asdfg5678
add another (y/n)?
instead of printing
asdfg1234
asdfg5678
shouldn't it output
hello1234
asdfg5678 ?
I'm just wondering why I'm getting asdfg instead of hello? Thanks!
#include <stdio.h>
#include <stdlib.h>
typedef struct {
const char *emp;
int num;
} InfoT;
int main () {
char* employee;
int number;
InfoT rank[20];
int size = 0;
if((employee = calloc(21, sizeof(char))) == NULL) {
return EXIT_FAILURE;
}
while(1) {
printf("Employee: ");
while (1) {
if (scanf("%s", employee) != 0)
break;
getchar();
}
printf("Employee number: ");
while (1) {
if (scanf("%d", &number) != 0)
break;
getchar();
}
rank[size].emp = employee;
rank[size].num = number;
printf("%s%d\n", rank[0].emp, rank[0].num);
printf("%s%d\n", rank[size].emp, rank[size].num);
printf("add another (y/n)?\n");
while (getchar() != '\n')
;
if (getchar() == 'n')
break;
size++;
}
return EXIT_SUCCESS;
}