跳过用C所有其他字符

跳过用C所有其他字符

本文介绍了的getchar()跳过用C所有其他字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在现在C.在这种情况下,我想读一行,并把该行的字符的到一个数组中充分利用的getchar()一会儿有问题。但是在分配的getchar()到阵列它跳过某些字符。

I have been having problems fully using getchar() for a while now in C. And in this case I am trying to read a line and put the char's of the line into an array. However upon assigning the getchar() to the array it skips some characters.

例如输入它会跳过所有其他输出...我的\\ n \\ n k键\\ n p \\ n \\ n v \\ n r \\ñ\\ N t个\\否E \\ n。 (成\\ n只是重新present新行)。

For example the input "It skips every other" the output is...I\n \n k\n p\n \n v\n r\n \n t\n e\n. (the \n is just to represent the new line.)

int N = 0;

char message[80] = {};

do
{
    message[N] = getchar();
    N++;
    printf("%c\n", message[N-1]);
}
while(getchar() != '\n');

感谢您的时间,如前面所说,几乎任何时候我曾经尝试过使用的getchar(),它总是给人一些意想不到的结果。我不完全了解函数如何读取字符的。

Thank you for your time, as stated before almost anytime I have ever tried to use getchar() it always gives some unexpected result. I don't fully understand how the function reads the char's.

推荐答案

您所呼叫的,而条件DO-,而体内的getchar()两次一个又一个。

You're calling getchar() twice one in the while condition and other inside the do-while body.

试试这个code来代替:

Try this code instead:

int N = 0;
#define MAX_SIZE 80

char message[MAX_SIZE] = {};
char lastChar;

do
{
    lastChar = getchar();
    if (lastChar == '\n')
        break;
    message[N] = lastChar;
    N++;
    printf("%c\n", message[N-1]);
}
while(N < MAX_SIZE);

更新:
增加了检查使用无限do-whil​​e循环数组的最大大小,而不是

UPDATE:Added checks for maximum size of the array instead of using an infinite do-while loop.

这篇关于的getchar()跳过用C所有其他字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:22