2015-08-31 33 views
1

我從正在使用的輸入中讀取字母和數字的程序。但我不知道如何實現這個.txt文件。這是我的代碼:從.txt文件讀取字母和數字

#include <iostream> 
    #include <string> 
    using namespace std; 

    int main() 
    { 
     char ch; 
     int countLetters = 0, countDigits = 0; 

     cout << "Enter a line of text: "; 
     cin.get(ch); 

     while(ch != '\n'){ 
      if(isalpha(ch)) 
       countLetters++; 
      else if(isdigit(ch)) 
       countDigits++; 
      ch = toupper(ch); 
      cout << ch; 
      //get next character 
      cin.get(ch); 
     } 

     cout << endl; 
     cout << "Letters = " << countLetters << "  Digits = " << countDigits << endl; 

     return 0; 
    } 

我在HW犯了一個錯誤,我想從.txt文件算的話,而不是字母。我在計算單詞時遇到了麻煩,因爲我對單詞之間的空間感到困惑。我怎麼能改變這個代碼來計算單詞而不是字母?我非常感謝幫助。

+0

做一個網上搜索 「C++閱讀文本文件」。嘗試自己做,並在出現具體問題時回到這裏。 – hoijui

回答

1

此代碼分別計算每個單詞。如果「單詞」的第一個字符是數字,它假定整個單詞是數字。

#include <iterator> 
#include <fstream> 
#include <iostream> 

int main() { 
    int countWords = 0, countDigits = 0; 

    ifstream file; 
    file.open ("your_text.txt"); 
    string word; 

    while (file >> word) {  // read the text file word-by-word 
     if (isdigit(word.at(0)) { 
      ++countDigits; 
     } 
     else { 
      ++countWords; 
     } 
     cout << word << " "; 
    } 

    cout << endl; 
    cout << "Letters = " << countLetters << "  Digits = " << countDigits << endl; 

    return 0; 
} 
+0

我必須使用相同的方法來計算數字嗎?目前這種方法也將數字計爲單詞。 –

+0

你確定你不會有任何混合數字和字母的單詞嗎?是的,它目前對每個單詞進行計數,無論是「數字」還是其他。 –

+0

我必須單獨計算單詞和數字,這是我卡住的地方。我感到困惑,因爲我不得不計算單個字母和數字。我們的教授說我們不會被要求閱讀諸如X2或student123這樣的字母組合。但是相反:貓是[那裏] \ n 10 20 3.1416,,1000 \ n(所有這些都在.txt文件中) –

0
#include <iostream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    char ch; 
    int countLetters = 0, countDigits = 0; 

    ifstream is("a.txt"); 

    while (is.get(ch)){ 
     if(isalpha(ch)) 
      countLetters++; 
     else if(isdigit(ch)) 
      countDigits++; 
     ch = toupper(ch); 
     cout << ch; 
    } 

    is.close(); 

    cout << endl; 
    cout << "Letters = " << countLetters << "  Digits = " << countDigits << endl; 

    return 0; 
} 
+0

非常感謝您的幫助!你會介意回答別的東西嗎?我的文本文件有3行:貓是[有] \ n 10 20 3.1416,,1000 \ n 另一隻貓\ n它能完美地讀取所有的字母和數字,但我怎樣讀取單詞而不是字母?我在HW中犯了一個錯誤,它要求數字而不是字母。 –