-
October 15th, 2013, 05:37 AM
#1
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
-
October 15th, 2013, 05:46 AM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|