将单个字符扫描到数组中 C 编程
我在将字符扫描到数组中时遇到问题。每次我这样做都会跳过下一次扫描并进入下一次。我知道发生了什么,因为输入还会在输入中添加“\n”,但我不知道如何纠正其原因。这是一些示例代码:
char charray [MAX], ffs;
int inarray [MAX], i;
for (i = 0; i < MAX; i++)
{
charray[i] = getchar();
printf ("%c\n",charray[i]);
scanf ("%d", &inarray[i]);
printf ("%d\n",inarray[i]);
}
I am having a problem scanning chars into an array. Every time I do it will skip the next scan and go to the next. I know what is happening because the input also adds '\n' to the input but I do not know how to remedy the cause of it. Here is some sample code:
char charray [MAX], ffs;
int inarray [MAX], i;
for (i = 0; i < MAX; i++)
{
charray[i] = getchar();
printf ("%c\n",charray[i]);
scanf ("%d", &inarray[i]);
printf ("%d\n",inarray[i]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做。
这可能会解决你的问题。或者你也可以一直到 EOF。
You can do like this.
this may solve your problem. or you can go till EOF also.
您正在使用 2 个函数读取标准输入:
getchar()
和scanf()
。您需要了解它们是如何工作的。getchar()
很简单:它返回输入流中的下一个可用字符(或等待一个字符或返回EOF
)scanf("%d", . ..)
更复杂:首先,它选择性地丢弃空格(空格、回车、制表符……),然后它读取尽可能多的字符来表示一个整数,并在第一个可以匹配的字符处停止。不能用于整数,例如'\n'
。当您将它们置于循环中时,您的
getchar()
调用将获取停止scanf()
的字符以及下一个scanf()
将从那里开始。如果您的输入类似于
"q1w22e333r4444"
(MAX == 4),您的程序将运行。如果您的输入类似于
第一次循环后的内容(其中
charray[0]
获取'q'
和inarray[0]
获取1
),getchar()
将获取'\n'
,而'w'
则“准备就绪” scanf,这当然会失败......然后被下一个“捕获”getchar()
;并且"22"
在第三次循环中被分配(到inarray[2]
)。因此,您需要检查您的代码。
此外,
scanf()
返回一个值。 使用该值You are reading from the standard input with 2 functions:
getchar()
andscanf()
. You need to understand how they work.getchar()
is easy: it returns the next available character in the input stream (or waits for one or returnsEOF
)scanf("%d", ...)
is more complex: first, it optionally discards whitespace (spaces, enters, tabs, ...), then it reads as many characters as possible to represent an integer, and stops at the first character that can't be used for integers, like a'\n'
.As you have them in a loop, your
getchar()
call will get the character that stopped thescanf()
and the nextscanf()
will procedd from there.If your input is something like
"q1w22e333r4444"
(with MAX == 4), your program will work.If your input is something like
after the first time through the loop (where
charray[0]
gets'q'
andinarray[0]
gets1
), thegetchar()
will get'\n'
leaving the'w'
"ready" for scanf, which of course fails ... and is then "caught" by the nextgetchar()
; and the"22"
gets assigned in the 3rd time through the loop (toinarray[2]
).So, you need to review your code.
Also,
scanf()
returns a value. Use that value实际上,您应该直接将字符串扫描到数组中,而不是使用
scanf("%s",&charray);
扫描字符。但是,如果您添加
while(getchar( ) != '\n' );
语句。这将获取 '\n' 之前的所有字符。You should actually scan a string into the array directly, rather than characters using
scanf("%s",&charray);
However your code will work if you add a
while(getchar() != '\n' );
statement. This will get all characters till the '\n'.