簡體   English   中英

如何解決不打印任何字符而只計算元音和字符並讀取文件中的每個字符的問題

[英]How to fix not printing any character and just count vowels and characters and read every character in a file

我只想讀取文件中的每個字符,我從 A 到 Z 放置字符,但程序每次打印 A 並計算元音 4 和字符 25 但期望打印元音 5 和字符 26 如何修復這個程序從最后修復4小時但沒有任何進展? 代碼:

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

using namespace std;

int main() {
  int i, count = 0, vowel_count = 0;
  string file_name;
  cout << "enter file name:";
  cin >> file_name;
  ifstream fin;
  fin.open(file_name);
  char ch;
  while (!fin.eof()) {
    fin.get(ch);
    cout << ch;
    while (fin >> ch) {
      i = ch;
      if ((i > 63 && i < 91) || (i > 96 && i < 123))
        count++;
      if (i == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
        vowel_count++;
    }
    cout << "\n No. of Characters in a File : " << count;
    cout << "\n No. of vowel characters in the File  : " << vowel_count;
  }
  fin.close();
  return 0;
}

您的代碼中有一些非常小的錯誤,我為您修復了這些錯誤。

此外,我添加了一個檢查文件是否可以打開。 這是大多數情況下的問題。

請看下面:

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

using namespace std;

int main() {
    int count = 0, vowel_count = 0;
    string file_name;
    cout << "\nEnter file name: ";
    cin >> file_name;
    ifstream fin(file_name);
    if (fin) {
        char ch;
        while (fin.get(ch)) {
            cout << ch;
            if ((ch >= 'A' && ch <= 'Z') || (ch > 'a' && ch <= 'z'))
                count++;
            if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
                vowel_count++;

        }
        fin.close();

        cout << "\n No. of Characters in a File : " << count;
        cout << "\n No. of vowel characters in the File  : " << vowel_count;
    }
    else std::cerr << "\n\n*** Error. Could notopen '" << file_name << "'\n\n";
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM