Oliver Tworkowski
Oliver Tworkowski

Reputation: 191

How can I read strings from a .txt file in a loop in C++

My Code:

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string index[8];

int main() {
    int count = 0;
    ifstream input;
    //input.open("passData.txt");
    while (true) {
        input.open("passData.txt");
        if (!input) {
            cout << "ERROR" << endl;
            system("pause");
            exit(-1);
        }
        else {
            if (input.is_open()) {
                while (!input.eof()) {
                    input >> index[count];
                    count++;
                }
            }
            for (int i = 0; i < 8; i++) {
                cout << index[i] << endl;
            }
        }
        input.close();
    }
    return 0;
}

My approach: opening the file in the beginning and then close it as soon as the lines where read. Also every line should be a single entry in the array.

However, I get an error in a file called "xutility" in an iterator. The output is the "passData.txt" file, only that its read once and then the error appears.

So, my question: how can I read every line of the file in an array entry, in a loop?

Thank you!

Upvotes: 0

Views: 1188

Answers (3)

Lion King
Lion King

Reputation: 33813

Look at the following code, I think it does your mission but it's simpler:

string strBuff[8];
int count = 0;
fstream f("c:\\file.txt", ios::in);
if (!f.is_open()) {
    cout << "The file cannot be read" << endl;
    exit(-1);
}
while (getline(f, strBuff[count])) {
    count++;
}

cout << strBuff[3] << endl;

Upvotes: 0

Caleth
Caleth

Reputation: 62531

When extracting from a stream, you should check the result, rather than testing beforehand.

You don't need to call open, the constructor that accepts a string does that. You don't need to call close, the destructor does that.

You should only output lines you have read.

Note that you should stop both if your file runs out of lines, or if you have read 8 lines

You can discard most of what you have written.

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    string index[8];
    std::size_t count = 0;   
    for(std::ifstream input("passData.txt"); (count < 8) && std::getline(input, index[count]); ++count)
    { 
        // this space intentionally blank
    }
    for(std::size_t i = 0; i < count; ++i)
    {
        std::cout << index[i] << std::endl;
    }
}

Upvotes: 0

pbn
pbn

Reputation: 2706

The problem I see with this code is that you don't break the endless loop, like ever. Because of that you keep on incrementing the count and it finally goes out of range for your string array called index.

Upvotes: 1

Related Questions