Find specific string of lines in a text file
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Find specific string of lines in a text file

  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
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,266

    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. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

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
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center