您的位置:首页 > 编程语言 > C语言/C++

【C语言】从文件每次读入一行字符串,并把这些字符串添加到字符串数组中

2016-05-11 22:48 190 查看

问题描述

从文件每次读入一行字符串,并把这些字符串添加到字符串数组中

测试文件rwq.txt

hello
jjjjj
ddddd
44444l
hello
hello
jjjjj
ddddd
jjjjj
ddddd

实现

读入一行之后需要处理末尾的
\n
,改成
\0


使用char* 数组来表示二维char数组

#include <stdio.h>
#include<string.h>
int main()
{
FILE * pFile;
char mystring [100];
char* res[999];    //store final result

int p=0;    //pointer of res[]
pFile = fopen ("rwq.txt" , "r");
if (pFile == NULL)
perror ("Error opening file");
else {
while ( fgets (mystring , 100 , pFile) != NULL )    //read a line every time

{
int len = strlen(mystring);
if(mystring[len-1]=='\n')
mystring[len-1] = '\0';

char* tmp = (char*)malloc(100*sizeof(char));
memcpy(tmp,mystring,len);//usage memcpy(dest, src, strlen(src));
res[p++] = tmp;
//puts (mystring);//put string every time
}
fclose (pFile);

//  int re_len = sizeof(res)/sizeof(res[0]);//wrong way to get arry lenth
//  printf("%d\n",re_len);
for(int i=0;i<p;i++)
printf("%s\n",res[i]);
}
return 0;
}

REF

C语言字符数组及其应用

一维数组每次添加一个elements

char* s = "hello";
int n = strlen(s);
char a[100];
for (int i=0;i<n;i++)
{
a[i]=*(s++);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: