简体   繁体   中英

How to read text file in C++ with 4 character?

I have following text file.

aaaaBBBBccccDDDDKKK
EEEEPPPPMMMMssssPPPP
AAAAEEEE
AAAAEEE
DDDDCCCC

And I have to read text file in c++ with divide four character.

and I want insert the four length character into string in one array.

For example, aaaa, BBBB cccc, DDDD, kkk, each word divided into array. string WordArray[N][M]

WordArray[0][0] = "aaaa";
WordArray[0][1] = "BBBB";
WordArray[0][2] = "cccc";
WordArray[0][3] = "DDDD";
WordArray[0][4] = "KKK";

WordArray[1][0] = "EEEE";
WordArray[1][1] = "PPPP";
WordArray[1][2] = "MMMM";
WordArray[1][3] = "ssss";
WordArray[1][4] = "PPPP";
.
.
.

WordArray[4][0] = "DDDD";
WordArray[4][1] = "CCCC";

How can I read text in upper way?

I want to use <fstream> .

Take a look at http://www.cplusplus.com/reference/istream/istream/read/

You could treat each block as 4 characters. Anyway you haven't specified even type of WordArray, so I assume it is flexy ( might be changed)

Let's say that you have successfully opened a file to: ifstream pFILE And let's say that your container is going to be defined as: vector<vector<string>> WordArray Then you can do something like this:

string line;

for(size_t word = 0U; pFILE; word = 0U) {
    getline(pFILE, line, '\n');
    WordArray.push_back(vector<string>()); 

    do {
        const size_t nextWord = line.find_first_not_of(line[word], word);

        WordArray.back().push_back(line.substr(word, nextWord - word));
        word = nextWord;
    } while(word != string::npos);
}

Live Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM