CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2013

    Find specific string of lines in a text file

    I am trying to print a specific line from a textfile

    I have a text file called info.txt and inside it contains the id,item name, price, quantity

    I know how to find a specific word at the line in the file but how do I find and print out the specific line e.g(print out just the entire contents of line 2)?

        string temDescription;
        ofstream fout;
        int curLine = 0;
        ifstream readFile("info.txt");
        cout << "Enter Item Description: "; 
        getline(cin, itemDescription);
        while(getline(readFile, line)) {
            if (line.find(itemDescription, 0) != string::npos) {
                 cout << "found: " << itemDescription << " at " << "line: " << curLine << endl;
    Please advise. thanks

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012

    Re: Find specific string of lines in a text file

    (print out just the entire contents of line 2)?
    Remove the if statement in the while loop and make a test on the value of CurLIne part of the while condition and ask for line number for input instead of Item Description. Once the while loop has completed, if no error on the file print the line.

    Before coding, you should design the program.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.7.2)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

By using this site, you agree to the Privacy Policy