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

Hybrid View

  1. #1
    Join Date
    Oct 2013
    Posts
    4

    Find specific string of lines in a text file

    I am trying to print a specific line from a textfile

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

    Code:
    1,shirt,100,10
    2,pants,50,9
    3,pen,20,8
    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)?

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

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    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++23 Compiler: Microsoft VS2022 (17.6.5)

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
  •  





Click Here to Expand Forum to Full Width

Featured