Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inputting from Textfile, Need to determine if word is on Next line???

Status
Not open for further replies.

p0gig

Technical User
May 29, 2006
2
US
Hey guys, I'm new here as I have a final project coming up and can't figure this out.. it sounds fairly simple

let's say I have a text file that reads

"Hello my name is Bob
I am Testing This Program
Hi there Bob"

I'm just using a simple ifstream loop to read the words as a string

is there anyway at all I can tell so that once my loop hits the word "I" so that I can tell that it's on the 2nd line? or when i hit "Hi", that i'm on the 3rd line?


Just incase this might help, my project is based on a Binary Search Tree, and the program is supposed to read the text file, and after each word is read, i'm supposed to have a pointer that points to an Integer that shows what line its on. So once it reads "Bob" over in the 3rd line.. the node "Bob" will have a pointer that points to "2" and then to "1".

so maybe i'm approaching this wrong?

Thanks for any help!
 
actually the node "Bob" will have a pointer that points to the int 3 and 1, because those are the lines that have Bob in it.

do i have to resort to using a char? (that would be mighty annoying.......) but even so, i tried a simple loop like

char a;
infile >> a;
if(a==' ')
cout << "SPACEEEEEEE";
if(a=='\n')
cout << "BREAKKKKKKK";

but that's not working either.. it wont detect a space or break...

hopefully i can get a solution that uses strings and not a char

thanks
 
It's a stream of char, so input stream operator >> does not know any lines.
If you want line numbers, make input loop on line by line basis: use getline() library function, for example:
Code:
int lineno;
string line;
for (lineno = 0; getline(cin,line); ++lineno)
{
   // Process the line word by word here...
}
To extract words use istringstream for <sstream>, for example (in loop body):
Code:
{
   istringstream ss(line);
   string word;
   while (ss >> word)
   {
      // Process word, use lineno counter...
   }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top