![](/img/trans.png)
[英]Reading lines from stdin into 2d array in C without knowing length of lines
[英]C reading lines from stdin
我的目标是使用 getline() function 从 piped.txt 文件中读取每一行,但每次使用此 function 时都会出现错误:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int Chars;
int size = 10;
char *string;
printf("Please enter a string: ");
string = (char*) malloc(size);
Chars = getline(&string, &size, stdin);
if (Chars == -1)
{
puts("ERROR!");
}
else
{
puts("You entered the following string: ");
puts(string);
printf("\nCurrent size for string block: %d", Chars);
}
return 0;
}
我总是收到错误代码:[Error] Id reruned 1 exit status
我已经重现了DevC++上的链接错误,即使在使用gcc编译器选项(例如-std=c11
)强制最近的 C 修订后, getline()
似乎也丢失了。
所以我用fgets()
重写了你的代码:
char *fgets(char *s, int size, FILE *stream);
它肯定比getline
更便携,但有一些区别:
size-1
字符(它会自动附加字符串终止符)。 所以它不管理缓冲区重新分配'\n'
字符(如果找到)#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_STR_SIZE 32
int main( void )
{
int len = 0;
char *str;
printf("Please enter a string: ");
str = malloc(MAX_STR_SIZE); /* (1) */
while( 1 )
{
size_t newline_pos;
fgets( str, MAX_STR_SIZE, stdin );
/* (2) */
if( len == 0) /* (3) */
{
puts("You entered the following string: ");
}
newline_pos = strcspn(str, "\n" );
str[newline_pos] = '\0';
len += strlen(str); /* (4) */
fputs(str, stdout);
if(newline_pos < MAX_STR_SIZE-1) /* (5) */
break;
}
printf("\n\nCurrent size for string block: %d", len);
free( str ); /* (6) */
return 0;
}
所以,基本上,我只是使用fgets
从stdin
读取,迭代直到找到'\n'
字符。 为了了解是否满足此条件,我使用strcspn() function,并使用相同的 function 从结果字符串中删除换行符。
一些注释/假设(检查代码部分中的相应数字):
malloc
的结果。 C中可以省略fgets
错误检查:它返回 NULL 以防出错(在找到 EOF 之前没有读取字符。它不会从标准输入读取)len==0
我们确保"You entered the following string: "
仅打印一次'\n'
时满足break
条件。 否则strcspn
的返回值为MAX_STR_SIZE
free
它是一个好习惯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.