i have problem trying to extracting the string from the text file. i knows how to read from the file but unable to extract the string which i want. i wanted to extract only the id out, how can i do it?

my text file format is below:

user:password,id,office

Two ways to do it that I can think of right off the top of my head
1) after reading the entire line, use std::string's find() method to locate the first comma then you will have the id field. Something like this

std::string line = "paciss0:abc,123,myoffice";
// locate the first comma
size_t pos = line.find(',');
// get the rest of the line
std::string id = line.substring(pos+1);
// remove everything after the 2nd command in the
// original string, leaving only id
pos = id.find(',');
id = id.substr(0,pos);

2) use std::stringstream with the line, then you can easily split it up using getline()

Comments
agreed

hi ancient dragon in your above mentioned code
std::string id = line.substring(pos+1);
cout << id << '\n';

here it doesnt displays the rest of the code that means the strings after , is not fetched by
std::string id = line.substring(pos+1);

another idea :

read the file until it encounter the word that you are looking for.
If found then stop else continue.

something like below. I am assuming your text file is like the one shown above.

bool findWord(char*Filename, string& find)
{
	ifstream iFile(Filename);
	if(!iFile)
	{
		cerr<<"File not opened!\n";
		return false;
	}

	char c;
	string content;

	while(iFile.get(c) )
	{
		if(c != ',')
		{
			content += c;
		}
		else content = ""; //reset string after flag ',' was found

		if(content == find)
			return true;

	}
	return false;
}

[EDIT] didn't see the "user:" part in your text. You can change it to start 1 after the file pointer reaches ':'. [/EDIT]

Edited 7 Years Ago by firstPerson: n/a

hi this the code am using for fetching lines in a text file till the deliminater

while (getline(ifs, line))

{

// locate the first occurrence of '*' in the line

// use string::npos if '*' is not found

string::size_type end = line.find_first_of('*');

// extract a substring up to the found '*'

// end==string::npos extracts the whole line

string command = line.substr(0, end);

cout << command <<'\n';

system(command.c_str());

// stop reading the file if '*' was found

if (end != string::npos) break;

}

i want the lines or section after the deliminater leaving the rest of the lines. so that i can get some part of section.

string command = line.substr(0, end);

in the above part the substring id fecthed from 0 to the end but i dont want it from the start ('0'). help me out

This article has been dead for over six months. Start a new discussion instead.