任务是从输入行的末尾删除空格和制表符以保持行数。不能使用字符串库。我已经做了我能做的一切,但在输出文件中第一行的末尾仍然有 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 中的任何地方使用。
至于你的代码然后设置 i
至 len - 2
不正确。
for (i=len-2; i>=0; i--){
^^^^^^
让我们假设 line1
仅包含换行符 '\n'
.在这种情况下 len
等于1
结果我将等于-1
.因此不会删除尾随的换行符。
关于c - 尾随字符行尾仍然在第一行末尾给出 0920,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702075/