我想得到文件内容,并把每一行在数组的项目 [英] I want to get file content and put each line in item of array

查看:114
本文介绍了我想得到文件内容,并把每一行在数组的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,此文件包含以下内容:



文件内容

  27013。 
Jake lexon。
8 Gozell St.
25/7/2013。
0.

我想将文件的内容保存到数组中,数组项如:

理论上

  
array [item1] = 27013.
array [item2] = Jake lexon。
array [item3] = 8 Gozell St.
array [item4] = 25/7/2013。
array [item5] = 0.



我尝试了很多,但是我失败了。 p>

编辑



使用c风格数组的原因是因为我想熟悉这两种方式 c-style数组向量不是简单的方法向量



编辑2



首先,调试器不会给我任何错误。
这是我使用的代码。

  fstream fs(accounts / 27013.txt,ios :: in); 
if(fs!= NULL){
char * str [100];
str [0] = new char [100];
int i = 0;
while(fs.getline(str [i],100))
{
i ++;
str [i] = new char [100];
cout<< str [i];
}
cin.ignore();
} else {
cout<< 错误。;
}

以及该代码的结果:

解决方案

当您需要一个解决方案,没有矢量(我不会喜欢)



  include< iostream> 
#include< fstream>
using namespace std;
int main()
{
fstream fs;
fs.open(abc.txt,ios :: in);
char * str [100];
str [0] = new char [100];
int i = 0;
while(fs.getline(str [i],100))
{
i ++;
str [i] = new char [100];
}
cin.ignore();
return 0;
}

注意:假设每行长度超过100个字符(包括换行符),且您的行数不超过100行。


I have a text file, this file contain the following:

The file content

27013.
Jake lexon.
8 Gozell St.
25/7/2013.
0.

I want to save the content of file into array, each line saved in item of array like:
Theoretically

new array;
array[item1] = 27013.
array[item2] = Jake lexon.
array[item3] = 8 Gozell St.
array[item4] = 25/7/2013.
array[item5] = 0.

I tried a lot but I failed.

Edit

The reason of using c-style array is, because I want to be familiar with both ways c-style array and vector not the easy way only vector.

Edit 2

Firstly the debugger doesn't give me any error. And this is the the code that I used.

fstream fs("accounts/27013.txt", ios::in);
if(fs != NULL){
    char *str[100];
    str[0] = new char[100];
    int i = 0;
    while(fs.getline(str[i],100))
    {
        i++;
        str[i] = new char[100];
        cout << str[i];
    }
    cin.ignore();
} else {
    cout << "Error.";
}

and the result of that code :

解决方案

AS YOU DEMAND A SOLUTION WITHOUT VECTORS.(Which I won't prefer at all)

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream fs;
    fs.open("abc.txt",ios::in);
    char *str[100];
    str[0] = new char[100];
    int i = 0;
    while(fs.getline(str[i],100))
    {
        i++;
        str[i] = new char[100];
    }
    cin.ignore();
    return 0;
}

NOTE: This assumes that each line is no longet than 100 characters(including newline) and you have no more than 100 lines.

这篇关于我想得到文件内容,并把每一行在数组的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆