I am trying to write a program where I could dynamically increase the size of a character pointer as the user enters each character into the console. Here is the program where I am attempting this concept: (A dynamically allocated string)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct Structure
{
char *buf;
int intvar1, intvar2;
};
char *getdt()
{
char *chr = (char*)malloc(1);
int i = 0;
char ch = getchar();
while (ch != '\n')
{
chr[i] = ch;
ch = getchar();
chr = (char *)realloc(chr, (++i) + 1);
}
chr[i] = '\0';
return chr;
}
void main()
{
int elmts = 0, i = 0;
Structure * strt;
scanf("%d", &elmts);
strt = (Structure*)malloc(sizeof(Structure)*elmts);
for (i = 0; i < elmts; i++)
{
strt[i].buf = getdt();
scanf("%d", &strt[i].intvar1);
scanf("%d", &strt[i].intvar2);
}
for (i = 0; i < elmts; i++)
{
printf("%s %d %f", strt[i].buf, strt[i].intvar1, strt[i].intvar2);
}
free(strt);
getch();
}
[The
getdt()
function is supposed to get a string from the user.]
The only trouble is with the following fragment:
strt[i].buf = getdt();
scanf("%d", &strt[i].intvar1);
scanf("%d", &strt[i].intvar2);
where I am able to retrieve a string properly at
strt[i].buf = getdt()
, but the successive scanf() 's skips and goes directly to the for-loop beneath.
After some researching I suspect the combination getchar() and scanf() would be the culprit. But I really dont understand what causes the malfunction.
Could any corrections be suggested ?
What I have tried:
This is what I have tried:
for (i = 0; i < n; i++)
{
strt[i].buf = getdt();
char tmp[10],tmp1[10], *tp,*tq;
getss(tmp);
strt[i].intvar1 = strtol(tmp,&tp,10);
gets(tmp1)
strt[i].intvar2 = strtol(tmp1,&tq,10)
}
These efforts were simply in vain.