从.txt文件中读取字母和数字
问题描述:
我的程序读取正在使用的输入中的字母和数字。但我不知道如何实现这个.txt文件。这是我的代码:
I program which reads the letters and numbers from the input being used. But i dont know how to implement this to a .txt file. This is my code:
#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文件中的字母。我有麻烦计数字,因为我困惑与字之间的空间。如何更改此代码来计算字而不是字母?非常感谢您的帮助。
答
此代码单独计算每个字。如果单词的第一个字符是数字,则假定整个单词为数字。
This code counts each word separately. If the first character of a "word" is a number, it assumes the entire word is numeric.
#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;
}