c++如何读取文本, 每一行存储到一个数组里面?

比如 code.txt 内容
abc
xyz
aaa

如何写一个小程序, 把 abc 存储到一个数组
例如 把 abc 存储到 a[0]
例如 把 xyz 存储到 a[1]

非常感谢!!

1、fopen函数可以读取文件,读到的每一行保存在字符数组中,根据空格作为分隔符进行分割。


2、例程:

#include <stdio.h>
#include <string.h>
#define MAXLINE 3
#define MAXCOLUMN 10
void main(void){
    FILE *fp; //文件指针
    char arr[MAXLINE][MAXCOLUMN]={0};  //定义3行10列的二维数组并初始化
    int i = -1;
    if((fp=fopen("./test/filename.txt","r"))==NULL){ //打开txt文件
        perror("File open error!\n");
        return;
    }
    while((fgets(arr[++i],MAXCOLUMN+1,fp))!=NULL) //读取一行并存到arr数组,百度fgets
        printf("%d: ",i); //打印行号
        //puts(arr[i]);
        char *subarr = strtok(arr[i]," ");  //以空格为分隔符从arr[i]中获得字串,百度strtok
        while(subarr!=NULL){
            data[i][j] = atoi(subarr);  //将字串转为int型数据存入data数组
            printf("%d\t",data[i][j]);  //打印data[i][j
            subarr = strtok(NULL," ");  //继续获得arr[i]中的字串
            j++;  //data数组列加一
        }
        printf("\n");    
    }
    //循环完毕后,所有数据已在data数组中
    printf("\n");
    fclose(fp);  //关闭指针
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-29
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

const unsigned int MAX_LINES = 1024;

int main()
{
    ifstream inFile;
    string tmpStr("");
    string *a = new string[MAX_LINES];
    int index = 0;
    inFile.open("./code.txt", ios::in);
    if (NULL == inFile)
    {
        cout << "文件打开失败!" << endl;
        return 1;
    }
    while (getline(inFile, tmpStr))
    {
        a[index] = tmpStr;
        index += 1;
    }
    for (int j = 0; j < index; j++)
    {
        cout << a[j] << endl;
    }
    delete [] a;
    return 0;
}

本回答被提问者采纳
第2个回答  2013-11-30
FILE *fp
char a[100];
if((fp = fopen("code.txt", "r") )== NULL)
{
cout<<"文件打开失败";
}
else{
for(i=0;!feof(fp);i++)
fscanf(fp,"%s",a[i]);
}

定义文件指针fp,读取code.txt中字符存入字符数组a[i]中,直到文件结束。追问

第一行少了个分号, 但是报错, 不能读

追答

我用输入法的时候没切换中英,你把分号都都更正过来,照着报错提示改是一定可以的。

第3个回答  2013-11-30
#include<iostream>
#include<fstream>
using namespace std;

const int MAX_LINES = 100;
const int MAX_CHARS_PER_LINE = 20;

int main()
{
    char str[MAX_LINES][MAX_CHARS_PER_LINE];
    ifstream ifs("code.txt");
    int i = 0;
    
    while (ifs>> str[i])
    {
        i++;
    }
    
    for (int j = 0; j < i; j++)
    {
        cout<< str[j]<<endl;
    }
    
    system("pause");
}