In: Computer Science
c++
How do I get it before a particular string when I use <ifstream>?
For example, when it's 'Apple: fruit', I only want to get the previous ':' text (Apple).
And then I want to move on to the next row.
How can i do?
Thanks for the question, For your requirement , you need to use getline function
I have demonstrated below as how to do it using a very simple file. Comments are included so that you can understand and apply on your own.
Refer the screenshot of the file and the output. I think this is what you were looking for.
Do let me know in case you need any further help.
=========================================================================
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream infile("D:\\veg.txt");
string name,junk;
// use getline to read upto a particular character in a line without reading that particular character ( here it is : )
// takes 3 arguments, stream, string variable and delimitting character
// reading stops just before the ':' character
// string before the character ':' get stored in the variable name
while(getline(infile,name,':')){
cout<<name<<endl;
// read the left over to a string variable, with delimiting character as new line character
getline(infile,junk,'\n');
// move to the next row
}
infile.close();
}