简体   繁体   中英

C++ getline() function bringing in whole file

I'm trying to search a document and find a subset to print out that particular line, however, it seems to pull in the whole message at once.

ifstream inputFile("searchfile.dat");

  int search;

  cout << "Enter what you're searching: ";
  cin >> search;

  string line;
  //bool notFound;

  while(getline(inputFile, line) /*&& notFound*/){
    if (line.find(search)) {
      cout << line << endl;
      //notFound = false;
    }
    //line = "";
  }


  inputFile.close();

This is a homework assignment, so I changed a few of my variables. Please keep that in mind when answering (ie explain what happened, so I can learn from this)

Thank you so much!

PS Here's the data I'm currently working with:

Name1  Name1  1000001  12.00
Name2  Name2  1000002  14.00
Name3  Name3  1000004  16.00

I need to search for the 1000000's number and print just the line. For example, I would search 1000002 and it would print: Name2 Name2 1000002 14.00

Right now it will print the whole thing

For a very basic fix do this

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

int main(){
    ifstream inputFile("searchfile.dat");

    string search;

    cout << "Enter what you're searching: ";
    cin >> search;

    string line;

    while(getline(inputFile, line) ){        
        if (line.find(search) != string::npos) {
            cout << line << endl;
        }
    }
}

The issues you had were twofold.

Firstly string::find doesn't return something which can be correctly evaluated in a boolean context. It returns the index at which the value can be found or otherwise string::npos . So if you check for that it will evaluate your if correctly.

The other issue is that you input search as an integer and then try to find it in a string. As a result it is calling this size_type find (charT c, size_type pos = 0) const; overload of find, which is trying to find a character. It happens this way because an int can be implicitly converted to a char. You should read in your id as a string or convert it to a string before using it with find .

Note a few other things. This code is a bit fragile as it will find that string anywhere on the line, so if a name or wage somehow contained that value it would be found. You also don't need to explicitly close the ifstream , it is closed in the destructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM