我的程序从正在使用的输入中读取字母和数字。但我不知道如何将其实现到 .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 文件中的单词而不是字母。我在数单词时遇到了麻烦,因为我对单词之间的空格感到困惑。我如何更改此代码以计算单词而不是字母?非常感谢您的帮助。
最佳答案
此代码分别计算每个单词。如果“单词”的第一个字符是数字,则假定整个单词都是数字。
#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;
}
关于c++ - 从 .txt 文件中读取字母和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304194/