-2

I have a txt file. Here is index:

1 A D C V K O F R W 
2 Y I J M 
3 Q P 
4 E S Z N L 

I got the letters in a variable called string readen[9];

readen[0]` = "A D C V K O F R W";
readen[1]` = "Y I J M";

Like this, there are blanks between them. I need to catch all the letters one by one like:

readen[0]` = "A";
readen[1]` = "W";

(Without blank)

Here is my code:

string read;
string readen[9];
char numbers[9];
ifstream file;
file.open("deneme.txt", ios::in);

for (int i = 0; !file.eof(); i++) 
{
    numbers[i] = file.get();
    file.get();
    getline(file,read);
    readen[i] = read;
}

As I said, It's like this now --> readen[0] = "A D C V K O F R W "

What's the best way to keep it like readen[0] = 'A' readen[1] = 'D' ?

Cortex0101
  • 831
  • 2
  • 12
  • 28
hoizery
  • 1
  • 1

2 Answers2

0
#include <cctype>  // std::isalpha()
#include <vector>
#include <iostream>
#include <fstream>

int main()
{
    std::ifstream is{ "deneme.txt" };
    std::vector<int> numbers;
    std::vector<char> letters;

    for (;;) {
        int number;
        int ch;

        // as long as extraction of an integer fails extract characters
        while (!(is >> number) && (is.clear(), (ch = is.get()) != EOF)) {
            if(std::isalpha(static_cast<unsigned>(ch)))
                letters.push_back(ch);
        }

        if (!is) break;

        numbers.push_back(number);
    }

    std::cout << "Numbers: ";
    for (auto const &n : numbers)
        std::cout << n << ' ';

    std::cout << "\nLetters: ";
    for (auto const &l : letters)
        std::cout << l << ' ';
    std::cout.put('\n');
}

Output:

Numbers: 1 2 3 4
Letters: A D C V K O F R W Y I J M Q P E S Z N L
  • Actually I want to keep them like `char numbers[4]; char letters[19];` and use them like `char x = letters[5]` I found a way but I'm doing something wrong. I tried `getline( file, read, ' ')` This way, I thought I could keep letters without blanks but the text was `A D C V K ` and what I get is `ACK`. Program stops and gives error. – hoizery Oct 28 '18 at 18:18
  • @hoizery "and use them like char x = letters[5]" you can use vectors the same way. –  Oct 28 '18 at 18:40
0

I solved it. I put in a loop. Everytime, letters[x] = file.get(); file.get(); First it takes the letter, than ignores 1 characters which is blank.

hoizery
  • 1
  • 1