-
User input?
I am new to programming in C but doing fairly well, I have created a structure and a doubly linked list, I think, and can get it to work. My problem seams to be in collecting the users input. I can use scanf to take in the data, but I don’t like the way it returns the curser to the next line to get the input, and have a problem taking in a string. I am using an array, but as you know with scanf it only reads to the first space. I have tried gets and because I am entering the info into a structure it gives me an error, some type of type conflict. I have thought of using gets to a pointer, but when I save my info will it only save the pointer or the info? Anyway I would be grateful for some ideas.
-
Using fgets( ) requires a buffer to read into. The same goes for it's "less safe" brother, 'gets'. Post a sample attempt, and we'll give you a hand.
For example:
char buf[256]={0};
fgets( buf, 256, stdin );
This will read into 'buf', a maximum of 255 characters, from the standard input device (keyboard).
Quzah.
-
Here is a copy of the code I have written to this point. I think the pointers and links work properly, if you see a problem with it let me know. Otherwise the problem I am having is with the user inputting the street address. Pleas help.
struct account {
int custID;
char lastname[25];
char firstname[25];
char street[50];
struct account *next;
struct account *prior;
};
struct account *first,*current,*newptr;
int idnum = 0;
void addNewAccount(void)
{
char buffer[64];
char *last;
newptr = (struct account *)malloc(sizeof(struct account));
if(first==(struct account *)NULL)
{
first = current = newptr;
current->prior = NULL;
}
else
{
current = first;
while(current->next != (struct account *)NULL)
current = current->next;
last = current;
current->next = newptr;
current = newptr;
current->prior = last;
}
idnum++;
printf("Cust ID:\n %i\n\n",idnum);
current->custID = idnum;
puts("Enter customer's last name: ");
scanf(" %s", current->lastname);
puts("\n");
puts("Enter customer's first name: ");
scanf(" %s", current->firstname);
puts("\n");
puts("Enter customer's street address: ");
/*scanf(" %s", current->street);*/
puts("\n");
system("pause");
current->next = (struct account *)NULL;
}
-
Similar to above, you should try modifying the input to use 'fscanf' to ensure that your user doesn't intentionally break your program. For example, for "lastname" I could enter:
33333333333333333333333333333333333333333333333333 33333333333333333333333333333333333333333333333333 33333333333333333333333333333333333333333333333333 33333333333333333333333333333333333333333333333333 33333333
and your program would puke.
Additionally, with fgets(), you'll not have to worry about it stopping on a space.
scanf( "%[^\n]", current->street );
That should work too. I think.
Quzah.