gets() does not read user input - c

I am new to linked list, now I have little problems in population of nodes.
Here I could populate first node of linked list but the gets() function doesn't seems to pause the execution to fill the next node.
Output is like:
Var name : var
Do you want to continue ?y
Var name : Do you want to continue ? // Here I cannot input second data
Here is my code:
struct data
{
char name[50];
struct data* next;
};
struct data* head=NULL;
struct data* current=NULL;
void CreateConfig()
{
head = malloc(sizeof(struct data));
head->next=NULL;
current = head;
char ch;
while(1)
{
printf("Var name : ");
gets(current->name); //Here is the problem,
printf("Do you want to continue ?");
ch=getchar();
if(ch=='n')
{
current->next=NULL;
break;
}
current->next= malloc(sizeof(struct data));
current=current->next;
}
}

This happens because:
ch=getchar();
read either y or n from the input and assigns to ch but there a newline in the input buffer which gets read by the gets in the next iteration.
To fix that you need to consume the newline following the y/n the user enters. To do that you can add another call to getchar() as:
ch=getchar(); // read user input
getchar(); // consume newline
Also the function fgets should be used in place of gets. Why?

It's exactly what #codaddict said. You need to clean the buffer.
void fflushstdin( void )
{
int c;
while( (c = fgetc( stdin )) != EOF && c != '\n' );
}
You can read this links that explains it very well:
c-faq
And this mdsn if you are on windows.
One more thing, try to always use fgets -instead of gets-, as it is impossible to prevent buffer overflows if you are using gets.
You could read the section "Use of safe libraries" at this link

you should also add a line like
current->next = 0;
after
current=current->next;
to ensure that the last element's next is not dangling.

Related

How to optimize reading character from input so the user does not need to specify the number of characters beforehand

Current state of program
I am making a program which reads the users input of chars until a new line and prints them out in reverse order.
The output i get is correct but i want to optimize the code.
In main i have written code that executes my Insert function n times (n represents the number of chars the user wants to input). So right now the user first need to input the amout of chars they want to input and then they can input the chars.
How i actually want it
I want to make it so that the user can just input the chars without having to first specify the number of chars they want to enter.
My attempts
Tried using a while loop but got wrong result:
Entered "asdf" as input
and got "fs" as output
int main(){
struct Node* head = NULL;
printf("Enter the chars you want to type: ");
while (getchar() != '\n') {
head = Insert(head,getchar());
}
Print(head);
}
Tried using a if statement but got wrong result:
Entered "asdf" as input
and got "s" as output
int main(){
struct Node* head = NULL;
printf("Enter the chars you want to type: ");
if (getchar() != '\n') {
head = Insert(head,getchar());
}
Print(head);
}
My code
#include <stdio.h>
#include <stdlib.h>
struct Node {
char data;
struct Node* linkToNext;
};
void Print(struct Node* head){
while (head != NULL) {
printf("%c", head -> data);
head = head -> linkToNext;
}
}
struct Node* Insert(struct Node* head, char input){
struct Node* pointerToNode = (struct Node*)malloc(sizeof(struct Node));
pointerToNode -> data = input;
pointerToNode ->linkToNext = head;
head = pointerToNode;
return head;
}
int main(){
struct Node* head = NULL;
int i, n;
printf("Enter the amout of chars you want to type: ");
scanf("%d", &n);
for (i = 0; i <= n; i++) {
head = Insert(head,getchar());
}
Print(head);
}
Example result of running code
Enter the amout of chars you want to type: 4
asdf
fdsa
Every call to getchar() reads and returns another character from the standard input.
Consider what happens with code like
while (getchar() != '\n') {
// ^^^^^^^^^ #1
head = Insert(head,getchar());
// ^^^^^^^^^ #2
}
and a user input of asdf.
The call labeled #1 reads and returns 'a' (the first character of input), which is not '\n', so the loop body is executed.
Then the call labeled #2 reads and returns 's' (the next character), which is added to the list.
Then we go back to the loop condition. getchar() #1 reads and returns 'd', which is still not '\n' ...
... and getchar() #2 reads and returns 'f', which is also added to the list.
Finally getchar() #1 reads a newline, which terminates the loop.
Because of the two calls to getchar in every iteration, only every second character was added to the list.
Your second attempt is similar, but if is not a loop, so only the second character total ('s' in asdf) was added to the list.
To fix this, you need to store the return value of getchar in a variable so you can compare it and add it to the list without reading more characters:
int c;
while ((c = getchar()) != '\n' && c != EOF) {
head = Insert(head, c);
}
The additional check for EOF is to prevent your program from going into an infinite loop in case the input is not terminated by '\n'.
you can do this using recursion.Just call the following function in your code.
void printRev(){
char a;
a = getchar();
if(a == '\n'){
return;
}
printRev();
putchar(a);
}
here you don't need for specifying the size of the input. you just scan until you hit enter then print during return.

How can i display stack C

How could I display stack when I insert x in to programs.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int Data;
struct Node* next;
} * top;
void popStack()
{
struct Node *temp, *var = top;
if (var == top)
{
top = top->next;
free(var);
}
else
printf("\nStack Empty");
}
void push(int value)
{
struct Node* temp;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->Data = value;
if (top == NULL)
{
top = temp;
top->next = NULL;
}
else
{
temp->next = top;
top = temp;
}
}
void display()
{
struct Node* var = top;
if (var != NULL)
{
printf("\nElements are as:\n");
while (var != NULL)
{
printf("\t%d\n", var->Data);
var = var->next;
}
printf("\n");
}
else
printf("\nStack is Empty");
}
int main(int argc, char* argv[])
{
printf(" Wellcome to Basic Stacking. \n");
top = NULL;
while (1)
{
when i insert "x" I want program to display stack and exit but it does not work after I insert x in this programs it will be infinite loop and don't display the stack and don't exit what should i do????.
char x ;
int value;
if (value != x)
{
printf("please enter Your Name:");
scanf("%d", &value);
push(value);
fflush(stdin);
display();
}
else
{
// popStack();
display();
break;
}
}
getch();
}
Some programmer dude already spotted, but I want to be a little more explicit:
char x;
int value;
if (value != x)
Both x and value are uninitialized, they could hold any value. If you compare them, it is very unlikely that they will match, but they could by accident even at the first time you enter the loop (leading to immediate exit). It is very unlikely, too, that variable x holds the value of 'x' – in the end, it is undefined behaviour anyway to read uninitialized variables...
Next problem is: You simply use scanf("%d"). This will fail trying to read input, if you type in an 'x' character, because that one cannot be scanned as a number. So you would have to read a string first and then parse it. Both errors fixed together, your code might look like this:
char buffer[128];
while(1)
{
if(!fgets(buffer, sizeof(buffer), stdin))
break; // some error occured
if(*buffer == 'x') // you can compare directly, you don't need a char x = 'x'; ...
break;
int value;
char c;
if(sscanf(buffer, "%d %c", &value, &c) == 1)
{
// ...
}
else
{
puts("invalid input");
fflush(stdout);
}
}
Scanning for an additional character after the number (important: the space character before is needed to skip white space, i. e. the terminating newline character got from fgets) together with checking the return value of sscanf detects invalid input such as 'abc' or '1xyz'.
Additionally, have a look at your popStack function:
struct Node* var = top;
if (var == top)
This will always be true, even it top is NULL: then var is NULL, too, and NULL is equal to itself, of course...
You should rather do it this way:
if (top)
{
struct Node* var = top;
top = top->next;
free(var);
}
Good practice is always checking the return value of malloc. Although it shouldn't ever fail in such a small program like yours, you won't forget it later when writing larger programs if you get used to right from the start...
Together with some code simplification (admitted, cosmetics only, but the if is not necessary...):
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
if(temp)
{
temp->Data = value;
temp->next = top;
top = temp;
}
else
{
// appropriate error handling
}
One last recommendation: Your two functions form a functional pair, so prefer reflecting this in their names, too: either "push" and "pop" or "pushStack" and "popStack".
I found out your problem! This was kinda of an headache since the program was always going for an infinite loop!
But the problem is you are reading characters with scanf("%d",&value). This scanf doesn't remove the input from the buffer, so every other scanf you do after will have the same input ('x'), which your scanf can't read.
To fix this change these lines:
printf("please enter Your Name:");
scanf("%d", &value);
to
printf("please enter Your Name:");
if(scanf("%d", &value)==0)value=x;
So if scanf isn't successful then you assume the user wants to exit.
This is also a duplicate question, lease refer to this question, for more details.
Your comparison of value against x always invokes undefined behaviour. The scope of value is the loop body. Effectively you get a "new" value each time you go round the loop.
Your scanf is looking for a number. If you expect the loop to terminate when you press the x key on your keyboard, it is not going to work. The scanf will actually fail because x is not a valid match sequence for %d. On the other hand, if you type in 120 which is the ASCII code for x you might get lucky and see the loop terminate because the undefined behaviour might include reusing the same location for value on each iteration of the loop.
To fix this, define read value before you do the comparison to see if it is x. Also, you'll have to read it using, for example fgets(), then check it to see if it x and then, if it isn't maybe use strtol() or sscanf() to convert it to a number.

Printf statments not printing in order

typedef struct node_s{
int data;
struct node_s *next;
}node_t;
void insert(node_t *pointer, int data){
while(pointer->next != NULL){
pointer = pointer->next;
}
pointer->next = (node_t *)malloc(sizeof(node_t));
pointer = pointer->next;
pointer->data = data;
printf("Elemnet inserted\n"); //2. Followed by this statment once done.
pointer->next = NULL;
}
int main(){
node_t *start, *temp;
start = (node_t *)malloc(sizeof(node_t));
temp = start;
temp->next = NULL;
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Print\n");
printf("4. Find\n");
while(1){
int input;
scanf("%d\n", &input);
if(input==1){
int data;
printf("Input data\n");//1. I want this to print out first once I give 1 input.
fflush(stdout);
scanf("%d", &data);
insert(start, data);
}
}
When I compile and execute, I can give inputs but the order of printf statements are not in sequence. For instance, this is how I get the output after I give input and enter the data.
sh-4.1$ ./linked_list
1. Insert
2. Delete
3. Print
4. Find
1
23
Input data
Elemnet inserted
1
45
Input data
Elemnet inserted
I tried adding fflush(stdout), after the printf statment as well.
Remove \n from the very first scanf
scanf("%d\n", &input);
What is that \n doing there? That is what is causing your scanf to "linger", waiting for extra input, instead of terminating immediately.
That \n has special meaning for scanf. When you use a whitespace character (space, tab or \n) in scanf format specifier, you are explicitly asking scanf to skip all whitespace. If such character is used at the very end of scanf format string, then after reading the actual data scanf will continue to wait for input until it encounters a non-whitespace character. This is exactly what happens in your case.
In addition to removing \n from your scanf statements, be aware that scanf will read the data from the command line, filling the variable specified, but it will leave the \n in the input buffer causing problems the next time scanf is called. Since there is no standard command to flush input buffers, you are responsible for insuring that you do not have extraneous unused characters in the input buffer the next time scanf is called. One simple way to handle manually flushing the input buffer after each scanf if to simply use getchar() to read any remaining characters in the input buffer until \n is encountered. For example:
int c;
...
scanf ("format", &var);
do {
c = getchar();
while ( c != '\n' );
This will insure subsequent calls to scanf retrieves the wanted data instead of passing the characters that remain in the input buffer.

Linked list trouble

Does anyone know what might be the problem with the following code? When I run it, I get the following output:
Insert a value in the list: 1
Do you want to continue? y/N:
1 ->
The fact is that the do-while loop executes until the scanf("%c", &ch) statement, and then it jumps out (so I cannot provide any input for the ch variable). I tried debugging with GDB and I got some weird messages:
GI___libc_malloc (bytes=16) at malloc.c:malloc.c: No such file or directory.
Also, it says that the compiler couldn't find the vscanf.c file. Does anyone have an explanation for this strange behavior? Thanks! (The intention was to print the values of a singly linked list in reverse order.)
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node* next;
};
struct node* head = 0;
void add_node(int value){
struct node* current = malloc(sizeof(struct node));
current->info = value;
current->next = head;
head = current;
}
void print_node(struct node* head){
while(head){
printf(" %d -> ", head->info);
head = head->next;
}
printf("\n");
}
int main(void){
int val;
char ch;
do {
printf("Insert a value in the list: ");
scanf("%d", &val);
add_node(val);
printf("Do you want to continue? y/N: ");
scanf("%c", &ch);
} while(ch == 'y' || ch == 'Y');
printf("\n");
print_node(head);
return 0;
}
If you want the input to be separated by a new line (which it appears that you do) then change the format of how you are reading in your character. Change following:
scanf( "%c", &ch );
... to this:
scanf( "\n%c", &ch ); // << Note, \n to pickup newline before reading the value.
You can check for proper input in an if-else block, and execute your code accordingly.
For example, here is something I would do if I needed to check whether the user wants to continue or not:
char chTemp; //Declare a test variable to check for newline
printf("Do you want to continue? y/N: ");
if (scanf("%c%c",&ch,&chTemp) != 2 || chTemp != '\n')
{
printf("Error in input (Integer input provided)");
}
else
{
//Do stuff.
}
Not only will it solve your problem, but it will also check for careless integer inputs.
The problem you are encountering is because the once you type a value for val and then press enter , then \n still remains in the input buffer . Hence , the next scanf assumes that \n which is still in the input buffer is its input , and consumes it and then loop exits .
Other Solutions :-
1) scanf("%d%*c",&val);
This would assign the first input character to val and then anything after that would be eaten up . Hence , the \n would not go into the next scanf
2) scanf("%[^\n]%*c",&val);
This would assign the anything to the val except \n and then \n would be eaten up .

Segmentation Fault during linked list in c

I am getting a segfault when I try and print out my linked list. Can anyone explain why? I am aware a segfault means that I am accessing memory I am not supposed to. I am assuming this means I am not setting up my pointers right. Any help would be great. My code...
#include <stdio.h>
#include <stdlib.h>
struct node
{
int val;
struct node *next;
}*head;
typedef struct node item;
int main() {
item *curr, *head;
head = NULL;
char word = 'y';
//int num[10];
//int i = 0;
while (word == 'y'){
printf("Would you like to enter an integer? (y/n) ");
scanf("%s", &word);
if(word == 'y'){
int temp = 0;
printf("Enter an integer: ");
scanf("%d", &temp);
curr = (item *)malloc(sizeof(item));
curr->val = temp;
if (head == NULL){
head = curr;
head->next = NULL;
}
else {
curr->next = head;
head = curr;
}
}
}
curr = head;
while(curr != NULL) {
printf("%d\n", curr->val); //seg fault happens here
curr = curr->next ;
}
return 0;
}
This:
scanf("%s", &word);
is a buffer overflow, since %s will read a string, but you only have a single character. This invokes undefined behavior; even if you enter just a single character, scanf() will add 0-termination after that character to make a proper string.
Change the declaration of word:
char word[32];
And scan with an explicit size, to prevent scanf() from writing outside the buffer:
scanf("%30s", word);
Also check the return values of all I/O and memory allocation calls, since they can fail.
Finally, don't cast the return value of malloc(), in C.
Regarding the memory leaks, can I suggest you fix them with the following code:
while(curr != NULL) {
item* temp = curr; // store the current pointer
printf("%d\n", curr->val);
curr = curr->next ;
free(temp); //free the current one now that curr points to the next
}
This frees the already printed head in each iteration of the loop.
The other issues are already addressed by other posters.
Initialize the *head pointer as
item *curr=NULL, *head = NULL;
without this, the if will not execute and you would access some random memory for head node. The while loop for printing the linked list may not terminate and keep accessing invalid memory.
if (head == NULL){
...
}
You have been caught out by scanf. First you wish to read a single character and the format for that is %c - %s reads the next non-blank sequence of characters after skipping any leading whitespace. Using %s causes the error, as it overwrites memory.
However if you change the format to %c your code still won't work, and it's scanf again. For most formats scanf will skip leading whitespace, but it does not do this when reading characters. So if you run your code you will see this:
Would you like to enter an integer? (y/n) y
Enter an integer: 10
Would you like to enter an integer? (y/n) 10
The second time around scanf has read the newline after the 10 into word, that is not a y, and then moved on to print out your list - the 10 at the end.
To skip whitespace before a character you add a space into the format string, so the line becomes:
scanf(" %c", &word);
That one change will allow your code to work but you should really do more checking. scanf will return the number of items it successfully found, you should check that to make sure the user really did enter a number etc., etc. As an example here is what happens if the user accidentally enters y twice:
Would you like to enter an integer? (y/n) y
Enter an integer: y
Would you like to enter an integer? (y/n) Enter an integer:
What has happened here is scanf("%d", &temp) failed, returned 0, and stored nothing into temp. However as you did not check the result your program continues and then the second y is consumed by the next scanf(" %c", &word).
Also look at your if (head == NULL) statement - this is not really necessary at all, you can replace the whole if/else with just two lines... that is left as an exercise.
HTH

Resources