How to read a file and get words in C ++

I am curious how I will read a word from a text file without a given structure (for example, notes or a small report) by word. For example, text can be structured as follows:

"05/06/1992
Today is a good day, the
Worm turned, and the battle was won."

I was thinking maybe getting a line using getline, and then see if I can break it into words with spaces. Then I thought using strtok might work! However, I do not think this will work with punctuation.

Another method I was thinking about was to get all char char and omit characters that were undesirable. But that seems unlikely.

So, to sort the short position: Is there an easy way to read input from a file and split it into words?

+1
source share
4 answers

Since it’s easier to write than to find a duplicate question,

#include <iterator>

std::istream_iterator<std::string> word_iter( my_file_stream ), word_iter_end;

size_t wordcnt;
for ( ; word_iter != word_iter_end; ++ word_iter ) {
    std::cout << "word " << wordcnt << ": " << * word_iter << '\n';
}

The argument std::stringfor istream_iteratortells him to return stringwhen you do *word_iter. Each time the iterator increases, it captures another word from its stream.

If you have multiple iterators in the same thread at the same time, you can choose between the data types to retrieve. However, in this case it’s easier to just use >>. The advantage of an iterator is that it can connect to common functions in <algorithm>.

+3
source

. std::istream::operator>>:) , , , .

.

std::ifstream file("filename");
std::vector<std::string> words;
std::string currentWord;
while(file >> currentWord)
    words.push_back(currentWord);
+3

getline , getline(buffer,1000,' ');

, , :

string StrPart(string s, char sep, int i) {
  string out="";
  int n=0, c=0;
  for (c=0;c<(int)s.length();c++) {
    if (s[c]==sep) {
      n+=1;
    } else {
      if (n==i) out+=s[c];
    }
  }
  return out;
}

: , using namespace std;.

s - , . sep i ( 0).

0

, ..... . (, , , ..) Parser.

, .

I can warmly recommend the book "Writing Compilers and Interpreters" by Ronald Mack (Wiley Computer Publishing)

0
source