c - 尾随字符行尾仍然在第一行末尾给出 0920

标签 c

任务是从输入行的末尾删除空格和制表符以保持行数。不能使用字符串库。我已经做了我能做的一切,但在输出文件中第一行的末尾仍然有 0920(使用八进制转储 od -x trim.out)任何想法它还有什么问题???

#define LINELIM 1000

int getLine(char s[], int lim);

int main (void){
    int  len, i;
    char line1[100];

    while ((len = getLine(line1, LINELIM)) >0){
            for (i=len-2; i>=0; i--){
            if (line1[i] == ' ' || line1[i] == '\t' || line1[i] == '\n'){
                   // professor says it is always true for some reason
                line1[i] = '\0';
            }
            else break;
        }

    if(line1[0]) // not a blank
        printf(" %s\n", line1);
    }

return 0;
}
/*getline: read a line into s, return length*/
int getLine(char s[], int lim){
    int c,i;
    for (i=0; i<lim-1 && (c=getchar())!= EOF && c!='\n'; ++i)
        s[i]=c;
    if (c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

最佳答案

首先你必须包含标题 <stdio.h> :

#include <stdio.h>

如果调用第二个参数等于LINELIM的函数

getLine(line1, LINELIM)

然后 line1必须定义相同的尺寸

char line1[LINELIM];

至于我,我会重写函数 getline以下方式:)

int getLine( char s[], int lim )
{
    int c;

    int i = 0;

    while ( i < lim - 1 && ( c = getchar() ) != EOF && ( s[i++] = c ) !='\n' ); 

    s[i] = '\0';

    return i;
}

main中的主循环可以这样写

while ( ( len = getLine( line1, LINELIM ) ) > 0 )
{
    int i = len;

    while ( i != 0 && ( line1[i-1] == ' ' || line1[i-1] == '\t' || line1[i-1] == '\n' ) ) --i;

    line1[i] = '\0';

    if ( line1[0] ) printf( "%s\n", line1 );
}

你应该移动i的声明从 while 循环中的 main 开始,因为除了这个 while 循环之外,变量没有在 main 中的任何地方使用。

至于你的代码然后设置 ilen - 2不正确。

for (i=len-2; i>=0; i--){
     ^^^^^^

让我们假设 line1仅包含换行符 '\n' .在这种情况下 len等于1结果我将等于-1 .因此不会删除尾随的换行符。

关于c - 尾随字符行尾仍然在第一行末尾给出 0920,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702075/

相关文章:

c - Sizeof 运算符与字符串一起使用来打印其长度

C 宏 : Conditional code based on parameter value?

C编程: a program that counts the number of words in a text file?

c - 从 valgrind 读取大小为 1 的内容无效

c - 在 C 中为结构数组重新分配内存

c - 如何在 C 中将两个 #define 作为关键字附加在一起?

c - C 中指针的困难

在 C 中作为参数传递的复合文字指针

c - 从文件中读取行不返回全部

c - gdb 目标远程 :1234 connection timeout linux