ANSI C - 如何从标准输入字字读? [英] ANSI C - how to read from stdin word by word?

查看:126
本文介绍了ANSI C - 如何从标准输入字字读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

#include <stdio.h>
int main(void) {
    char i[50];
    while(scanf("%s ", i)){
        printf("You've written: %s \n", i);
    }
    printf("you have finished writing\n");

    return 0;
}

一个问题是,因为预计到code不做。如果我输入:

One problem is that the code doesn't do as it is expected to. If I typed in:

abc def ghi.

这将输出:

You've written: abc
You've written: def

我该如何解决?我们的目标是从标准输入读取每一个字,直到达到ENTER或。 (点)。

How can I fix it? The goal is to read every single word from stdin until it reaches "ENTER" or a "." (dot).

推荐答案

@cnicutar是pretty接近,但你显然只想要开始在比空白等,阅读的东西,想停止读取一个字当你到空白,所以对于你扫描集,你可能想要的东西更像是:

@cnicutar is pretty close, but you apparently only want to start reading at something other than white-space, and want to stop reading a single word when you get to whitespace, so for you scanset, you probably want something more like:

while(scanf(" %49[^ \t.\n]%*c", i)) {

在此,最初的存储空间,在前面的空白跳过。扫描设置然后读取,直到它到达一个空格,制表符,换行符或期限。的%* C然后读取(但扔掉)的下一个字符(通常是停止扫描的)。

In this, the initial space skips across any leading white space. The scan-set then reads until it gets to a space, tab, new-line or period. The %*c then reads (but throws away) the next character (normally the one that stopped the scan).

这可以,但是,扔掉一个字​​符当/如果你到达缓冲区的末尾,所以你可能需要使用%C,并提供一个字符读入来代替。这将让你从一个单一的词比你提供的缓冲区再恢复。

This can, however, throw away a character when/if you reach the end of the buffer, so you may want to use %c, and supply a character to read into instead. That will let you recover from a single word longer than the buffer you supplied.

这篇关于ANSI C - 如何从标准输入字字读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆