#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<vector>
#define N 3 //3列
#define L 16000 //66000行
#define MOVIES "D:\\FilmReview\\movies.dat" //電影資料 1::Toy Story (1995)::Adventure|Animation|Children|Comedy|Fantasy MovieID::Title::Genres
#define RATINGS "D:\\FilmReview\\ratings.dat" //用戶評分資料 1::122::5::838985046 UserID::MovieID::Rating::Timestamp
#define MODE "D:\\FilmReview\\mode.dat"
#define A "D:\\FilmReview\\a.dat"
char data[L][N]={}
using namespace std;
void main()
{
FILE *fp;
//char (*data)[N];//指向陣列的指標
//data = new char[L][N];
//
//char* data[L];//指標的陣列
//for(int i=0; i<L; i++)
// data[i] = new char[N];
//vector<vector <char> > data(L ,vector<char>(N));
//char **data;
//data=https://bbs.csdn.net/topics/(char **)malloc(L*sizeof(char *));
//for(int i=0;i<L;i++)//定義二維陣列
// data[i]=(char*)malloc(512*sizeof(char *));
int i=0, j=0 ,count=0;
char *buf=(char *)malloc(2048*sizeof(char*));
char *p=(char *)malloc(2048*sizeof(char*));
if((fp=fopen(A, "rb")) == NULL) //打開檔案
{
printf("請確認檔案(%s)是否存在!\n", MOVIES);
exit(1);
}
fseek(fp, 0, SEEK_SET);
while(fgets(buf,2048*sizeof(char),fp)!=NULL)//讀入一行資料
{
printf("%s",buf);
//sscanf(buf,"%[0-9]::%[A-z([0-9]):]::%[A-z]",&data[count][0],&data[count][1],&data[count][2]);//格式化一行資料 存入陣列
i=0;
p = strtok(buf, "::");
data[count][i]=*p;
while((p = strtok(NULL, "::"))){
data[count][++i]=*p;
if(i==N-1)
i=0;
}
printf("%s %s %s\n",data[count][0],data[count][1],data[count][2]);
count++;
}
fclose(fp);
for(i = 0; i < count; i++) //輸出陣列內容
{
printf("第%d列元素為: ", i+1);
for(j = 0; j < N; j++){
printf("%c ", data[i][j]);
}
printf("\n");
}
free(buf);
free(data);
system("pause");
}
這是我的一個檔案讀取,然后存入陣列的代碼。
第一張圖是我的檔案的格式:MovieID::Title::Genres
第二張圖是我的debug中各個變數運行中的值,然后我發現,是在data[count][i]=*p;,也就是把切割出來的值存入陣列的時候,里面只存入了每個切割點的第一個字符。
第三張圖是我的運行結果圖。求各位大神幫忙看下,怎么才能把切割出來的值完整的存入到陣列里面去。一開始我還以為是陣列的問題,以為建立的char陣列,沒有分配記憶體,只有默認是sizeof(char *)的位元組也就是4個位元組。但后面發現不管我怎么分配記憶體,還是這樣的效果,所以我也是很頭大,搞了好幾天,后面試試用map容器把存入資料,但最后發現出來的也都是亂碼。求各位大神的幫助。這是我另一個帖子:http://bbs.csdn.net/topics/392147037 你們也可以去看看。謝謝~


轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/63010.html
標籤:基礎類
上一篇:求助簡單回圈佇列問題,c++
下一篇:剛開始學習C語言呼叫外部函式,老是出現這個錯誤[Error] ld returned 1 exit status
