stackuser
stackuser

Reputation: 11

read data from file to vector array(only specific lines!)

how to modify my readFromFile function to have output like below? My .txt looks like:

1
2
3
4
5

I want my output to be like this:

1
2
4

Output im getting now:

blank blank blank   1 2 3 

main.cpp:

int main()
{

    std::fstream myFile;
    openFile(myFile);
    std::vector<int> V = readFromFile(myFile);

    for (size_t i = 0; i < V.size(); i++)
    {
        std::cout<<V[i]<<"\n";
    }

    myFile.close();
}

function:

std::vector<int> readFromFile(std::fstream &myFile)
{

    vector<int> V;
    int i = 0, x;
    if (myFile.is_open())
    {
        while (i != 4)
        {
            if (i == 0 || i == 1 || i == 3)
            {
                myFile >> x;
                V.push_back(x);
                i++;
                std::cout << "\n";
            }
            else
            {
                i++;
                std::cout << "\n";
            }
        }
    }
    return V;
}

Upvotes: 1

Views: 33

Answers (2)

Roman Kwaśniewski
Roman Kwaśniewski

Reputation: 483

Your code reads the numbers for i equal to 0, 1 and 3 in sequence and throws them into the vector, and for other values your code does nothing so your code reads the numbers 1, 2 and 3 in turn and writes them in the vector. If you want to omit 3, you should also read it, but do not save it in the vector. Here is the correct code:

std::vector<int> readFromFile(std::fstream &myFile)
{

vector<int> V;
int i = 0, x;
if (myFile.is_open())
{
    while (i != 4)
    {
        if (i == 0 || i == 1 || i == 3)
        {
            myFile >> x;
            V.push_back(x);
            i++;
            std::cout << "\n";
        }
        else
        {

            myFile >> x;
            i++;
            std::cout << "\n";
        }
    }
}
return V;

}

Upvotes: 1

scohe001
scohe001

Reputation: 15446

Notice that the only time you read a value from your file (and so advance the file pointer) is when i == 0 || i == 1 || i == 3. So even though you're incrementing i, your file pointer still hasn't moved!

Instead, I'd change your logic around so you read from the file no matter what (and so move forward in it), but only store the value if it's one you're looking for:

while (i != 4)
{
    myFile >> x;
    if (i == 0 || i == 1 || i == 3)
    {
        V.push_back(x);
    }
    i++;
}

Upvotes: 1

Related Questions