我想要的是一个多行文本输入,并能够计算小写字母,大写字母,句号,逗号,空格,换行符和其他字符的数量。输入。
我试图在while循环中只使用一个带getline的字符串输入,每个标点符号类别都有一个运行计数。
我只是不知道如何实际计算每行中每种字符类型的数量。给定一个字符串,我如何计算每种类型的数量?
到目前为止,这是我的代码(显然不完整):
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main(){
cout << "This program takes any number of sentences as inputs. " << endl;
cout << "It will count the number of lower-case letters and upper-case letters. " << endl;
cout << "It will also count the number of periods, exclamation marks, spaces, end-lines, etc. " << endl;
cout << " " << endl;
cout << "Please type your text, pressing enter whenever you wish to end a line. " << endl;
cout << "Use the EOF key (CTRL + Z on Windows) when you are finished. " << endl;
string InputString; // This is the string that will be used iteratively, for each line.
int NumberOfLowerCase = 0;
int NumberOfUpperCase = 0;
int NumberOfSpaces = 0; // spaces
int NumberOfTabs = 0; // tabs
int NumberOfPeriods = 0; // periods
int NumberOfCommas = 0; // commas
int NumberOfOtherChars = 0; // other characters
int NumberOfEnters = 0; // end of line, will be incremented each loop
do {
getline(cin, InputString); // input
cout << InputString << endl; // filler just to test the input
NumberOfLowerCase = NumberOfLowerCase + 0 // I don't know what I should be adding
// (obviously not zero, that's just a filler)
} while (!cin.eof() && cin.good());
system("pause");
return 0;
}
答案 0 :(得分:1)
如果您只想要唯一字符的数量,请使用set
!您可以将所有角色都推入到集合中,然后只需检查集合的大小,您就可以开始了!
如果你真的想知道每个角色中有多少你可以使用map
(实际上它使用了一套装置!)。使用地图,给定一些字符c
,您可以执行
std::map<char, int> counter;
//do stuff...
counter[c]++; //increment the number of character c we've found
//do more stuff...
std::cout << "Found " << counter['A'] << " A's!" << std::endl;
答案 1 :(得分:1)
请参阅these有用的功能。在这里你会做什么:
config/secrets.yml
答案 2 :(得分:0)
这是我写得很快的一个非常简单的例子。当然有更好的方法,但这应该让你知道如何做到这一点。一个问题:您是直接从控制台读取文件还是从istream读取文件?
int lowerCase = 0;
int upperCase = 0;
int spaces = 0; // spaces
int tabs = 0; // tabs
int newLines = 0; // end of line, will be incremented each loop
int periods = 0; // periods
int commas = 0; // commas
int otherChars = 0;
// read from istream, char by char
for (char ch; cin >> noskipws >> ch;) {
// test which classification or char ch is and increment its count
if (islower(ch))
++lowerCase;
else if (isupper(ch))
++upperCase;
else if (ch == ' ')
++spaces;
else if (ch == '\t')
++tabs;
else if (ch == '\n')
++newLines;
else if (ch == '.')
++periods;
else if (ch == ',')
++commas;
else
++otherChars;
}
cout << "Number of characters of each type:\n";
cout << "lowerCase:\t" << lowerCase << '\n'
<< "upperCase:\t" << upperCase << '\n'
<< "spaces:\t\t" << spaces << '\n'
<< "tabs:\t\t" << tabs << '\n'
<< "periods:\t" << periods << '\n'
<< "commas:\t\t" << commas << '\n'
<< "newLines:\t" << newLines << '\n'
<< "otherChars:\t" << otherChars << '\n';