【发布时间】:2021-01-25 15:40:36
【问题描述】:
// C++ program to count the uppercase
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
// Function to count uppercase
int Count ( string str )
{
int upper = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] >= 'A' && str[i] <= 'Z')
upper++;
}
return upper;
}
// Driver function
int main()
{
//Open the file
ifstream openedFile;
//This is how you turn the potential file into an actualized file inside the defualt directory.
openedFile.open ( "random words.txt" );
string str[10001]; int i = 0;
int uppercase = 0;
while (!openedFile.eof())
{
getline ( openedFile, str[i], '\n');
uppercase = Count(str[i]);
if (Count(str[i]) == 1) uppercase++;
if (Count(str[i]) == 3) uppercase++;
if (Count(str[i]) == 2) uppercase++;
cout << Count(str[i]) << "\n";
}
cout << "Uppercase letters: " << uppercase << endl;
//Close the file
openedFile.close ();
}
表示出现大写字母。有时甚至连3个。但它不会添加到大写变量中。
【问题讨论】:
-
while (!openedFile.eof())会导致您多读 1 行。 https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons -
uppercase = Count(str[i]); if (Count(str[i]) == 1) uppercase++; if (Count(str[i]) == 3) uppercase++; if (Count(str[i]) == 2) uppercase++;的目的是什么? -
string str[10001]你真的需要一个数组吗? -
如果
i永远不会改变并且没有理由保留数据,那么数组是什么? -
您可能永远不会看到它失败的情况,但
if (str[i] >= 'A' && str[i] <= 'Z')会在一个连续的块中使用 AZ 的字符集,其中 A first 和 Z last,这并不能保证。跨度>
标签: c++ file capitalization letter alphabet