我有下一个练习:编写一个程序来打印超过10个字符的所有输入行。
我写了这个:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
#define NEED 10 //minimum lenght of a line to be printed
int main()
{
int len;//length of last line
char line[MAXLINE];//current line
char lines[1000];//array with all lines
int i;//current array zone for write
i = 0;
while ((len = getline(line, MAXLINE)) > 0)//get one line from user
if (len > NEED){//if length of its is bigger than NEED
i = copy(line, lines, i);//write character by character in lines
}
printf("%s", lines);//print lines
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)//get the line
s[i] = c;//character by character
s[i] = '\n';//and add new line(\n) at last of its
return i;//return length of line
}
// copy a character array to another and return last wrote zone of array
int copy(char from[], char to[], int i)
{
int j=0;
while(from[j] != '\0'){
to[i]=from[j];
i++;
j++;
}
return i;
}
当我运行这个,我输入几行大于10个字符,程序打印行和一些更奇怪的字符。我张贴一个链接到一个照片看。为什么会发生这种事?
发布于 2014-04-16 07:26:29
在getline()
函数中
s[i] = '\n';
您在字符串末尾添加了\n
(换行符),但是字符串应该以\0
结尾(C中的字符串被这个字符终止),所以请使用,
s[i] = '\0';
发布于 2014-04-16 07:44:31
另外,在将整个数据复制到最后的一个新字符串(行)后,您必须追加一个'\0'
字符。
lines[i] = '\0';
printf("%s", lines);//print lines
发布于 2015-05-22 01:44:06
请参阅下面编写的"getline“函数
int getline(char s[], int lim) //Reads line into s and returns its length
{
int c,i;
//Performs error checking to not exceed allowed limit
for(i=0;i<lim-1 && ((c= getchar())!=EOF) && c!='\n';++i)
s[i] = c;
if(c == '\n') //We add newline only if it's entered
{
s[i] = c;
++i;
}
s[i] = '\0'; //Puts null char to mark the end of string
return i;
}
我们使用
if(c=='\n')
确保仅在按enter键时才将新行存储在数组中,并将其与EOF区分开来,并超过最大输入大小1000。
不管有什么输入,一旦我们走出了"for“循环,
s[i] = '\0'
必须用于将此空字符追加到字符串的末尾。此语句用于确保数组知道何时结束,以便在程序的后面部分我们可以使用它作为引用来查找数组的结尾及其大小。
对于主程序,下面的代码应该足够打印输出,而不是使用“复制”函数。
if(len>MAXNEED)
printf("Printed line - %s - ", lines);
https://stackoverflow.com/questions/23102602
复制相似问题