从stdin读取并存储\ n和空格

时间:2013-08-31 18:25:31

标签: c

我一直在尝试使用scanf从stdin获取输入,但是在看到空格或点击返回后它会截断字符串。

我想要的是一种读取存储在缓冲区换行符和空格中的键盘输入的方法。并在按下ctrl-D时结束。

我应该尝试使用fgets吗?我认为这不会是最佳的,因为在读取\ n

之后fgets会返回

4 个答案:

答案 0 :(得分:1)

scanf()在空白边界处分割输入,因此它不适合您的情况。确实fgets()是更好的选择。你需要做的是在fgets()返回后继续阅读;每次通话都会读取一行输入。您可以继续阅读,直到fgets()返回NULL,这意味着无法再读取任何内容。

如果您希望逐个字符地输入,也可以使用fgetc()。当没有更多内容可以阅读时,它将返回EOF

答案 1 :(得分:1)

没有现成的函数来读取stdin中的每一个,但幸运的是,创建自己的函数很容易。未经测试的代码片段,在注释中有一些解释,可以从stdin读取任意大量的字符:

size_t size = 0; // how many chars have actually been read
size_t reserved = 10; // how much space is allocated
char *buf = malloc(reserved);
int ch;

if (buf == NULL) exit(1); // out of memory

// read one char at a time from stdin, until EOF.
// let stdio to handle input buffering
while ( (ch = getchar()) != EOF) {

    buf[size] = (char)ch;
    ++size;

    // make buffer larger if needed, must have room for '\0' below!
    // size is always doubled, 
    // so reallocation is going to happen limited number of times
    if (size == reserved) {
        reserved *= 2;
        buf = realloc(buf, reserved);
        if (buf == NULL) exit(1); // out of memory
    }
}

// add terminating NUL character to end the string,
// maybe useless with binary data but won't hurt there either
buf[size] = 0;

// now buf contains size chars, everything from stdin until eof,
// optionally shrink the allocation to contain just input and '\0'
buf = realloc(buf, size+1);

答案 2 :(得分:0)

像这样阅读

char ch,line[20];  
int i=0;  //define a counter

 //read a character assign it to ch,  
 //check whether the character is End of file or not and   
 //also check counter value to avoid overflow.

while((ch=getchar())!=EOF && i < 19 )   
{
   line[i]=ch;
   i++;
}
line[i]='\0';

答案 3 :(得分:0)

如果您想要阅读所有输入,无论是否是空格,请尝试fread