迭代C中stdin的字符串

时间:2015-12-10 20:30:44

标签: c iteration scanf stdin

我想阅读stdin的前20个字符。我是否能够使用迭代20次且scanf("%c",&var)的for循环?如果输入长度少于20个字符会发生什么?

我在考虑使用gets()来绕过这个问题。读入整行,然后迭代字符串,直到计数器达到20或达到字符串结尾。但是,有没有办法可以检测到字符串的结尾?

或者有更好的方法吗?

只是问这个,因为我们不允许使用string.h库中的任何功能。

4 个答案:

答案 0 :(得分:1)

你可以这样试试......

1 - 使用scanf()读取一行的前20个字符,如下面给出的字符数组中的示例所示。

例如:

  char str[21];

  scanf("%20[^\n]s",str);

2 - 最后,你的角色阵列中将有前20个字符。

3 - 如果线路长度小于20,那么它将自动分配' \ 0'行尾的字符。

如果要查找数组中的总字符数,则计算数组的长度

**字符串的结尾是通过使用' \ 0'来确定的。空字符

答案 1 :(得分:1)

以下是使用基本 fgetc 的解决方案:

#include <stdio.h>

#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))

static void ReadLine(FILE *file, char result[], int resultLen)
{
    int i, ch;

    ch = fgetc(file);
    i = 0;
    while ((ch != EOF) && (ch != '\n') && (i < resultLen - 1)) {
        result[i] = ch;
        ch = fgetc(file);
        i++;
    }
    result[i] = '\0';
}


int main(void)
{
    char s[20 + 1];

    ReadLine(stdin, s, LEN(s));
    puts(s);
    return 0;
}

答案 2 :(得分:0)

这是一个使用scanf的简短版本:

#include <stdio.h>

int main(void) {
    char buffer[20 + 1] ; // 20 characters + 1 for '\0'
    int  nread ;
    nread = scanf("%20[^\n]", buffer) ; // Read at most 20 characters
    printf("%s\n", buffer);
    return 0;
}

scanf会自动在'\0'的正确位置添加buffer字符,而"%20[^\n]"会在最多 20个字符处添加'\n'字符与20不同。

如果你想把它放在一个函数中并且避免重复#include <stdio.h> int read_chars (char buffer[], int len) { char format[50] ; sprintf(format, "%%%d[^\n]", len); return scanf(format, buffer) ; } #define MAX_CHARS 20 int main(void) { char buffer[MAX_CHARS + 1] ; // 20 characters + 1 for '\0' read_chars (buffer, MAX_CHARS) ; printf("%s\n", buffer); return 0; } (容易出错):

sprintf

编辑:如果您不想使用MAX_CHARS创建格式字符串,则可以使用预处理器(如果#include <stdio.h> #define _READ_CHARS(buffer, N) scanf("%" #N "[^\n]", buffer) #define READ_CHARS(buffer, N) _READ_CHARS(buffer, N) #define MAX_CHARS 20 int main(void) { char buffer[MAX_CHARS + 1] ; // 20 characters + 1 for '\0' READ_CHARS (buffer, MAX_CHARS) ; printf("%s\n", buffer); return 0; } 不是预处理器常量,则无法使用):

{{1}}

答案 3 :(得分:0)

只需使用阅读:

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>

    int main(){
        //Declare the reading buffer. Need 1 more position to add '\0'
        char buffer[21];

        int char_num;
        if ((char_num = read(0, buffer, 20)) < 0) {
            perror("read: ");
            exit(1);
        }
        //means that there were less than 20 chars in stdin
        //add the null character after the last char and return
        else if (char_num < 20) {
            //terminate the string after the last char read from stdin
            buffer[char_num] = '\0';
            close(0);
            printf("%s\n", buffer);
        }
        //means that there were more than 20 (or exactly 20 chars on stdin)
        else {
            buffer[20] = '\0';
            printf("%s\n", buffer);
            //now it depends on what you want to do with the remaining chars
            //this read just discard the rest of the data, in the same buffer
            //that we ve used. If you want to keep this buffer for some other
            //task, figure out some other solution
            while(1) {
                if ((char_num = read(0, buffer, 20)) < 0) {
                    perror("read: ");
                    exit(1);
                }
                close(0);
                if (char_num == 0 || char_num < 20)
                    break;
            }
        }
        return 0;
    }