c语言多行字符串输入
时间: 2025-02-19 15:33:25 浏览: 63
### C语言中实现多行字符串输入的方法
在C语言中,为了能够处理多行字符串输入,可以采用动态分配内存的方式逐行读取并存储每一行的内容。下面展示了一种具体的做法:
#### 动态分配内存逐行读取
通过定义一个结构体用于保存每行的数据以及整个文档的信息,这样不仅方便管理还易于扩展。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 1024 // 定义单行最大长度
typedef struct Line {
char *content;
} Line;
typedef struct Document {
int line_count;
Line **lines;
} Document;
// 创建新行对象
Line* create_line() {
Line *line = (Line *)malloc(sizeof(Line));
if (!line) exit(-1);
line->content = NULL;
return line;
}
// 添加一行到文档中
void add_line_to_document(Document *doc, const char *str) {
doc->line_count++;
doc->lines = realloc(doc->lines, sizeof(Line*) * doc->line_count);
Line *new_line = create_line();
new_line->content = strdup(str); // 使用strdup复制字符串内容
doc->lines[doc->line_count - 1] = new_line;
}
int main(void){
Document document;
document.line_count = 0;
document.lines = NULL;
size_t buffer_size = MAX_LINE_LENGTH;
char *buffer = malloc(buffer_size);
printf("请输入多行文本(结束输入请按Ctrl-D):\n");
while(getline(&buffer,&buffer_size,stdin)!=EOF){ // 获取一行数据
strip_newline(buffer); // 去除可能存在的换行符
add_line_to_document(&document, buffer); // 将获取的一行加入到Document中
}
free(buffer);
// 输出所有已读入的行
for(int i=0;i<document.line_count;++i){
printf("%s\n",document.lines[i]->content);
}
// 清理资源
for(int i=0;i<document.line_count;++i){
free(document.lines[i]->content);
free(document.lines[i]);
}
free(document.lines);
return 0;
}
```
此代码片段展示了如何创建`Document`和`Line`两个结构体来分别代表一个多行文本及其单独一行;并通过循环调用`getline()`函数不断从标准输入流读取直到遇到文件结束标志(`EOF`)为止[^3]。每次成功读取一行之后都会去除掉潜在的换行符,并将其添加至当前正在构建的`Document`实例里去。最后遍历打印出所有的行作为验证操作的结果。
阅读全文
相关推荐


















