2017-01-10 49 views
0

我正在尝试编写一个C++程序,其中计算每个单词中字符数(不仅仅是总体中所有字符的总和)的数量。我无法准确定义一个单词何时开始和结束(使用字符)时遇到问题。我怎样才能改写这个循环,以便识别一个单词并将其中的字符数添加到名为“word?”的变量中这是我到目前为止有:C++在文本文件的每个单词中查找字符数

#include <iostream> 
    #include <fstream> 
    #include <string> 
    using namespace std; 
    int main(){ 
    ifstream fin("file.txt"); 
    int word=0; 
    char ch; 
    while(fin && ch!= '.'){ 
    if(ch==' ' || ch=='\n') 
    word++; 

这是错误的,因为某些文字可能有哪些,通过这个循环中,将被算作一个字字符空格的大部分。感谢您的帮助!

回答

1

请记住,正常输入运算符>>跳过空格。

这意味着您可以读入std::string对象并为每个这样的“单词”增加计数器。

0

你也只能增加字长,如果在你的循环当前字符是字母使用isalpha(ch);

例01:

#include <string> 

using std::string; 

string Sentence = "I'm trying to write a C++ program where the number of characters in each word individually (not just the sum of all characters overall) of a text file is counted."; 

int main() { 

    unsigned WordLength(0); 

    for (auto i = Sentence.begin(); i != Sentence.end(); ++i) { 
     if (isalpha(*i)) 
      ++WordLength; 
    } 

    return 0; 
} 

当然,你必须自己决定如果您想要将C++中的+或者'字符作为单词的一部分,或者添加逻辑来忽略这些字符。你也可以使用isspace(ch)。只有在信件不是空格时才算数。但是,那么你需要确保你忽略标点符号等,你可以使用ispunct(ch)。但是你仍旧需要逻辑照顾的特殊情况下,像''+'或其他字符,你可能要算或不算:d

例02:

unsigned WordLength(0); 

for (auto i = Sentence.begin(); i != Sentence.end(); ++i) { 
    if (isspace(*i) || ispunct(*i)) { 
     /// Print length of word then reset 
     WordLength = 0; 
    } 
    else { 
     ++WordLength; 
    } 
} 

无论如何,希望能帮助到你! :D

0

你可以做这样的事情。

#include<bits/stdc++.h> 
using namespace std; 
int main() 
{ 
    string temp; 
    int word=0; 
    ifstream inf("new.txt"); 
    while(inf.good()){ 
     inf>>temp; 
     if(inf.eof()) 
      break; 
     word+=temp.length(); 
    } 
    cout<<word; 
    return 0; 
} 

将文本文件逐字读出并复制到'temp'字符串中。如果你只是计算所有单词的字母,那么你只需要计算字符串。 对于其他操作(对于任何或某些特定的字母),您可以检查'temp'字符串。

相关问题