不打印数组的第一个元素

问题描述 投票:0回答:1

我正在为“C 编程语言”编写一个程序 - 练习 1-17。尽管没有将一些东西变成自定义函数,但我的问题是我的代码没有打印或写入数组的第一个元素。

#include <stdio.h>

#define maxCharacters 1000
#define printCondition 10 // the line will only be printed if it is >= printCondition


//int getLine()

int main()
{
    int c;
    int l = 0; //length of the line in numbers
    int i = 0;

    char lastLine[maxCharacters];
    
    while(getchar() != EOF)
    {

        for (i = 0; i < maxCharacters - 1 && (c = getchar()) != EOF && c!='\n'; i++)
            lastLine[i] = c;
        
        if (c == '\n')
        {
            lastLine[i] = c;
            ++i;
        }
        
        lastLine[i] = '\0';
        
        
        if (i > printCondition)
        {
            printf("%s", lastLine);
        }
        
        else
            printf("zu kurz\n");
    }
}

谢谢大家

arrays c
1个回答
0
投票

出现您遇到的问题是因为 您在循环内调用 getchar() 两次:一次在 while 条件中,一次在 for 循环中。第一次调用 getchar() 消耗第一个字符,第二次调用从第二个字符开始读取,有效地跳过第一个字符。

#include <stdio.h>

#define MAX_CHARACTERS 1000
#define PRINT_CONDITION 10 // the line will only be printed if it is >= printCondition

int main() {
    int c;
    int l = 0; // length of the line in numbers
    int i = 0;

    char lastLine[MAX_CHARACTERS];
    
    while ((c = getchar()) != EOF) {
        for (i = 0; i < MAX_CHARACTERS - 1 && c != EOF && c != '\n'; i++) {
            lastLine[i] = c;
            c = getchar(); // read the next character
        }
        
        if (c == '\n') {
            lastLine[i] = c;
            ++i;
        }
        
        lastLine[i] = '\0';
        
        if (i > PRINT_CONDITION) {
            printf("%s", lastLine);
        } else {
            printf("zu kurz\n");
        }
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.