I want to get file content and put each line in it

2019-08-28 16:36发布

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 : enter image description here

标签: c++ file
3条回答
乱世女痞
2楼-- · 2019-08-28 16:55

The approach is straighforward:

// container
vector<string> array;

// read file line by line and for each line (std::string)
string line;
while (getline(file, line))
{
   array.push_back(line);
}

// that's it
查看更多
仙女界的扛把子
3楼-- · 2019-08-28 17:02

You can read each line into a vector of strings, using std::getline:

#include <fstream>
#include <vector>
#include <string>

std::ifstream the_file("the_file_name.txt");

std::string s;
std::vector<std::string> lines;
while (std::getline(the_file, s))
{
    lines.push_back(s);
}
查看更多
冷血范
4楼-- · 2019-08-28 17:08

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.

查看更多
登录 后发表回答