在getchar()函数之后,Scanf()失败。 [英] Scanf() fails after getchar() function.
问题描述
我正在尝试编写一个程序,当用户将每个字符输入控制台时,我可以动态增加字符指针的大小。这是我尝试这个概念的程序:(一个动态分配的字符串)
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();
}
[ getdt()
函数应该从用户那里得到一个字符串。]
唯一的问题是使用以下片段:
[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);
我可以在<$ c $正确检索字符串c> strt [i] .buf = getdt(),但是连续的scanf()跳过并直接进入下面的for循环。
经过一番研究后,我怀疑组合getchar()和scanf()将是罪魁祸首。但我真的不明白导致故障的原因。
可以建议更正吗?
我尝试过:
这就是我的尝试:
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.
推荐答案
为什么要为自己复杂化?使用获取,_getws [ ^ ]读取字符串。这是scanf
的常见问题,它与其他控制台字符输入调用无关;获取
应该避免这个问题,因为它会清除输入缓冲区。
Why complicate things for yourself? Use gets, _getws[^] to read a string. This is a common problem withscanf
, it does not fir well with other console character input calls;gets
should avoid this problem as it clears the input buffer.
这篇关于在getchar()函数之后,Scanf()失败。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!