从.txt文件中读取字母和数字
Reading letters and numbers from .txt file
从正在使用的输入中读取字母和数字的程序。但我不知道如何实现这到。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文件中计算单词而不是字母。我数单词有困难,因为我搞不清单词之间的空格。我怎样才能改变这个代码来计算单词而不是字母呢?
此代码分别计算每个单词。如果"word"的第一个字符是数字,则假定整个单词都是数字。
#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;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char ch;
int countLetters = 0, countDigits = 0;
ifstream is("a.txt");
while (is.get(ch)){
if(isalpha(ch))
countLetters++;
else if(isdigit(ch))
countDigits++;
ch = toupper(ch);
cout << ch;
}
is.close();
cout << endl;
cout << "Letters = " << countLetters << " Digits = " << countDigits << endl;
return 0;
}
相关文章:
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 如何读取具有数字间隔的文本文件?C++
- 如何将uint8_t的二进制表示形式读取为数字
- C++ - 将 int 读取为字母和数字序列
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 我可以从具有不同数字分隔符的istream中读取双值吗
- 如何从文件中读取用空格分隔的数字
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 将任意大小的大量 Base-10 数字读取到位集中
- 无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字
- 将字符串和数字读取到向量C
- C++ 将文件中的数字读取到数组中,然后将其打印到其他数组中
- 将数字读取到矢量
- (c++)试图将数字读取到数组中,在输出中得到垃圾数字
- 在读取文件时,在增加数组大小的同时,将浮点数字读取到动态分配的中
- 猜数字 - 读取错误时无限循环