Printf statments not printing in order - c

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.

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.

Loop that inputs characters in an array of structures does not work properly

The dictionary program should read the word(s) that the user inputs as either the "word" or "definition." The only problem is that for the first instance of the loop, the readLine function does not seem to be called, and this only happens when the word has to be stored in dictionary[0].word. It skips letting the user input the word for Entry #1.
How can I fix this?
// Enter words with their corresponding definitions
#include <stdio.h>
struct entry
{
char word[15];
char definition[50];
};
int main (void)
{
int numberEntries;
void inputEntry (struct entry dictionary[], int numberEntries);
printf ("How many dictionary entries do you want to enter?.\n");
scanf ("%i", &numberEntries);
struct entry dictionary[numberEntries];
inputEntry (dictionary, numberEntries);
return 0;
}
void inputEntry (struct entry dictionary[], int numberEntries)
{
void readLine (char buffer[]);
int i;
for ( i = 0; i < numberEntries; i++ ) {
printf ("Entry #%i:\n", i + 1);
printf ("Word: ");
readLine (dictionary[i].word);
printf ("Definition: ");
readLine (dictionary[i].definition);
printf ("\n");
}
for ( i = 0; i < numberEntries; i++ ) {
printf ("\n%s", dictionary[i].word);
printf ("\n%s", dictionary[i].definition);
}
}
// Get a string and save it in an array
void readLine (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar ();
buffer[i] = character;
i++;
}
while ( character != '\n' );
buffer[i - 1] = '\0';
}
You are mixing use of scanf and getchar which is confusing things. The scanf will only read the integer that is typed, and then the next getchar will read the Enter keypress as a \n.
The easiest solution in your case would be to use readLine instead of scanf.
You may also consider the use of the standard function fgets instead of writing your own readLine. fgets is better because your function does not do bounds checking on the buffer parameter, leading to buffer overruns if you type too many characters on one line.
Another way to strip the newline from the input buffer after using scanf is to use getchar(). This is recommended any time you need to read a second time from stdin:
char c;
...
scanf ("%i", &numberEntries);
do {
c = getchar();
} while ( c != '\n');
You will then be able to enter the first word without problems:
./bin/dict
How many dictionary entries do you want to enter?.
3
Entry #1:
Word: dog
Definition: wags tail
Entry #2:
Word: cat
Definition: meows constantly
Entry #3:
Word: mouse
Definition: does little
dog
wags tail
cat
meows constantly
mouse
does little

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

gets() does not read user input

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.

Resources