Home > database >  Can't filter out string vector in writing txt file in C
Can't filter out string vector in writing txt file in C

Time:10-17

I want to read a text file that contains both text and number, and after reading it, write some data from that file into a new text file that contains the last 3 numbers of each row only. If there is a text of "120, Hello, Hi", I want to skip it and write only the last 3 numbers after "Hi", and enter a new line after writing these 3 numbers. Here I use string vector to read it, but I can't get the format I want to write to. How can I write it into my wanted format? Any help would be appreciated.

Input text file:"mytext.txt"

120

Hello

Hi 55 66 44

Hi 1 2 3

Hi 11 22 33

Hi 111 222 333

Wanting Format: "mynewtext.txt"

55 66 44

1 2 3

11 22 33

111 222 333

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
    vector<string> VecData;
    string data;

    ifstream in("mytext.txt");

    while (in >> data) {
        VecData.push_back(data);
    }
    in.close();

    ofstream mynewfile1("mynewtext.txt");
    for (int i = 0; i < VecData.size(); i  ) {
        if ((VecData[i] != "120") || (VecData[i] != "Hello") || (VecData[i] != "Hi")) {
            mynewfile1 << VecData[i] << " ";
        }
    }

    mynewfile1.close();

    return 0;
}

CodePudding user response:

The issue here is that you're checking that VecData[i] is not "120", or it's not "Hello", or it's not "Hi". This will always be true.

Think about the case where VecData[i] is "Hi":

if ((VecData[i] != "120") ||     // (1)
    (VecData[i] != "Hello") ||
    (VecData[i] != "Hi"))

The comparison at (1) has evaluated to True, since "Hi" != "120".

What you should be doing is checking that it isn't "120" AND it isn't "Hello" AND it isn't "Hi", like so:

if ((VecData[i] != "120") &&
    (VecData[i] != "Hello") &&
    (VecData[i] != "Hi"))
  • Related