-
input output problems
hi I am working with input and output with text files. I am able to read one word in a file.
Code:
char thing;
ifstream fin( "workerslog.txt" );
while(fin.get(thing))
{
cout << thing;
}
cout << endl;
fin.close();
but i want to know if there is a way to look for words in their fullness, because I want to be able to have a text file that says
Joe
3 5 6 7
Mike
5 6 9 2
and have the user type in the name and the program will find the name in the text file and list the information. I looked at the getline function but i don't understand cppreference.com's definition. Is there a function that seeks out words in a text file?
-
If you use the operator>> it will get each word separated by whitespace. So if you had "I am 72 years old.", you would get "I", "am", "72", "years", and "old.". If you output them back you would have to of course output your own spaces.
You could also use getline and then search for the word inside the line. I am assuming you are using the standard string class (if not then it is a little different and in my opinion harder). Use getline to get a line into a string, then use the find member function for the string to find your word. Don't forget to make sure the word is not part of a larger word by checking the character before and after it.
-
>Is there a function that seeks out words in a text file?
grep...but that won't help you much. getline is the way to go:
Code:
#include <string>
string find;
string line;
getline ( cin, find );
while ( getline ( fin, line ) && find != line )
;
// At this point you're right after the line you were looking for in fin
// Or you're at EOF :), so let's add this:
if ( !fin.eof() ) {
// Do your thing
}
Using C strings:
Code:
#include <string.h>
char find[SIZE]; // You define SIZE to something sane
char line[SIZE];
cin.getline ( find, sizeof find );
while ( cin.getline ( line, sizeof line ) && strcmp ( find, line ) != 0 )
;
if ( !fin.eof() ) {
// Do your thing
}
-
thank you for the advice it worked