0

I've read the lines from a textfile and i want to check if that line contains the $ sign.

That's what i got so far:

int main() {

    ifstream data_store;
    string line;
    data_store.open("c:\\test.txt");


    while (!data_store.eof())
    {

        getline(data_store, line);
        if (line.find("$"))
        cout << "1: " << line << endl;
    }


    data_store.close();

    system("PAUSE");
    return 0;
}

Furthermore how can i output them to a file ?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Nassif Bousaba
  • 386
  • 1
  • 4
  • 22

3 Answers3

2

To check if a line contains something using std::string::find to need to check the returned value from find to make sure it is a valid return. To do that we compare it against std::string::npos as that is what find() will return if it does not find anything. This is the reason it finds every line as std::string::npos is still considered true when evaluated as a bool. So refactoring your code you would have:

while (getline(data_store, line))
{
    if (line.find("$") != std::string::npos)
        cout << "1: " << line << endl;
}

I also changed the while loop as using eof is not how to control a while loop. for more information on that see Why is “while ( !feof (file) )” always wrong?

As far as outputting the string to a file see: How to write std::string to file?

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

It's a minor thing, but a variant of @NathanOliver's solution, is to use a for loop:

ifstream data_store("c:\\test.txt");

for ( string line; getline(data_store, line); ) {
  if ( line.find("$") != string::npos )
    cout << "1: " << line << endl;
}
// ...

The benefit here is that line is now local only to the loop, which is what it should be since that is the only place it is used.

KyleKnoepfel
  • 1,426
  • 8
  • 24
0

I did it yesterday forgot to update.

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

using namespace std;

bool contains_number(const string &c);



int main()
{
    int count = 0;
    {
        string line1[100];
        ifstream myfile("D:/Users/Jarvan/Desktop/test.txt");

        int a = 0;

        if (!myfile)
        {
            cout << "Error opening output file" << endl;
            system("pause");
            return -1;
        }

        while (!myfile.eof())
        {
            getline(myfile, line1[a], '\n');

            if (contains_number(line1[a]))
            {
                count += 1;
                cout << line1[a] << "\n";
            }
            else cout << "\n";
        }
    }

    cout << count <<endl;


    system("pause");
    return 0;
}



bool contains_number(const string &c)
{
    return (c.find_first_of("$") != string::npos);
}
Nassif Bousaba
  • 386
  • 1
  • 4
  • 22