2014-10-05 3 views
0

Я хотел бы получить совет/помощь в отношении разделения абзаца из отдельного текстового файла на собственные строки. Код, который у меня есть до сих пор, просто подсчитывает общее количество слов в этом абзаце, но я хотел бы разбить его, чтобы каждая строка была 1 предложением, а затем подсчитала количество слов в этом предложении/строке, а затем поместила это в свой собственный массив, чтобы я может делать другие вещи с этим конкретным чувством/линией. Вот что у меня есть код мудрый:Разделение абзаца отдельного текстового файла на отдельные строки

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 
int main() 
{ 
std::ifstream inFile; 
inFile.open("Rhymes.txt", std::ios::in); 
if (inFile.is_open()) 
{ 
    string word; 
    unsigned long wordCount = 0; 

    while (!inFile.eo()) 
    { 
     inFile >> word; 
     if (word.length() > 0) 
     { 
      wordCount++; 
     } 
    } 

    cout << "The file had " << wordCount << " word(s) in it." << endl; 
} 


system("PAUSE"); 
return 0; 
} 

Отдельный текстовый файл называется «Rhymes.txt» и содержит:

Today you are You, that is truer than true. There is no one alive who is Youer than You. 
The more that you read, the more things you will know. The more that you learn, the more places you'll go. 
How did it get so late so soon? Its night before its afternoon. 
Today was good. Today was fun. Tomorrow is another one. 
And will you succeed? Yes indeed, yes indeed! Ninety-eight and three-quarters percent guaranteed! 
Think left and think right and think low and think high. Oh, the things you can think up if only you try! 
Unless someone like you cares a whole awful lot, nothing is going to get better. It's not. 
I'm sorry to say so but, sadly it's true that bang-ups and hang-ups can happen to you. 

Таким образом, первая линия будет его собственное предложение и когда код выполнен, он сказал бы:

The line has 19 words in it 

Я немного смущен как тоже, как бы я это сделал. Я видел примеры раскалывания предложений в слова, но я не мог найти ничего, что я мог бы понять, что связано с тем, что я прошу.

+0

Это "отдельный", а не "индивидуальный". –

ответ

0

В предположении, что каждое пустое пространство является ровно одним пустым символом, и нет пламени/klemping, вы можете рассчитывать через std::count. Чтение в строках можно сделать через std::getline.

int main() 
{ 
    // Simulating the file: 
    std::istringstream inFile(
R"(Today you are You, that is truer than true. There is no one alive who is Youer than You. 
The more that you read, the more things you will know. The more that you learn, the more places you'll go. 
How did it get so late so soon? Its night before its afternoon. 
Today was good. Today was fun. Tomorrow is another one. 
And will you succeed? Yes indeed, yes indeed! Ninety-eight and three-quarters percent guaranteed! 
Think left and think right and think low and think high. Oh, the things you can think up if only you try! 
Unless someone like you cares a whole awful lot, nothing is going to get better. It's not. 
I'm sorry to say so but, sadly it's true that bang-ups and hang-ups can happen to you.)"); 

    std::vector<std::string> lines; // This vector will contain all lines. 

    for (std::string str; std::getline(inFile, str, '\n');) 
    { 
     std::cout << "The line has "<< std::count(str.begin(), str.end(), ' ')+1 <<" words in it\n"; 
     lines.push_back(std::move(str)); // Avoid the copy. 
    } 

    for (auto const& s : lines) 
     std::cout << s << '\n'; 
} 

Если вам нужно количество слов в каждом предложении позже, сохранить std::pair<std::string, std::size_t>, чтобы сохранить как линию и количество слов - изменить тело цикла к этому:

 std::size_t count = std::count(str.begin(), str.end(), ' ') + 1; 
     std::cout << "The line has "<<count<<" words in it\n"; 
     lines.emplace_back(std::move(str), count); 
0

Я написать что-то вроде:

vector<string> read_line() 
{ string line, w; 
    vector<string> words; 

    getline(cin, line); 
    stringstream ss(line); 

    while(ss >> w) 
    words.push_back(w); 

    return words; 
} 

Возвращенного вектор содержит информацию, необходимую: подсчет слов и сами слова (с пунктуацией, которые вы можете легко удалить).

vector<string> words = read_line(); 
cout << "This line has " << words.size() << " words in it" << endl; 

Чтобы прочитать все строки, которые вы делаете:

while(1) 
{ vector<string> words = read_line(); 
    if(words.size() == 0) break; 

    // process line 
} 
Смежные вопросы