我需要帮助将逗号和句点作为.txt文件中的空格读取。该程序运行平稳,输出正确数量的单词和数字,但我需要将句号和逗号作为单独数字读取的数字。
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, char* argv[]) {
int countWords = 0, countNumbers = 0;
ifstream file;
file.open ("input1.txt");
string word;
while (file >> word) // read the text file word-by-word
{
if (isdigit(word.at(0))) // if the first letter a digit it counts as number
{
countNumbers++;
}
else
{
countWords++;
}
cout << word << " ";
}
cout << endl;
cout << "Words = " << countWords << " Numbers = " << countNumbers << endl;
system("pause");
return 0;
}
答案 0 :(得分:2)
不是逐字阅读,而是可以读取所有行并逐个字符地迭代它。因此,当您找到空白,点或逗号时,您可以检查它是单词还是数字。
因此,您可以使用函数 getline 来读取一行并迭代所有字符。代码如下所示:
while (getline(file, line))
{
string currentWord;
char currentChar;
for (int i = 0; i < line.length(); i++)
{
currentChar = line[i];
if (currentChar == ' ' || currentChar == ',' || currentChar == '.')
{
if (currentWord != "")
{
// check if currentWord is composed by letters or numbers here
}
currentWord = "";
}
else
{
currentWord += currentChar;
}
}
}
也许您还需要检查currentChar是否与&#39; \ r&#39;不同。或者&#39; \ n&#39;。另一个选择是检查currentChar是否既不是字母也不是数字。
另外,请务必在阅读后关闭文件。
答案 1 :(得分:1)
这是您新修改的问题的解决方案。我采用的方法是遍历每个字符串并计算数字或单词,考虑到句点和逗号应被视为空格。与previous question中一样,我假设某个单词不能由字母或数字组合而成。换句话说,如果第一个字符是数字,那么整个单词就是一个数字,否则它就是一个字符单词。
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void countWord(const string& word, int &countNumbers, int &countWords);
int main(int argc, char* argv[]) {
int countWords = 0, countNumbers = 0;
ifstream file;
file.open ("input1.txt");
string word;
while (file >> word) {
// iterate over each "word"
countWord(word, countNumbers, countWords);
cout << word << " ";
}
cout << endl;
cout << "Words = " << countWords << " Numbers = " << countNumbers << endl;
system("pause");
return 0;
}
void countWord(const string &word, int &countNumbers, int &countWords) {
bool word_start = true;
for (int i=0; i < word.length(); i++) {
if (word_start == true) {
if (word.at(i) == '.' || word.at(i) == ',') {
continue;
}
else if (isdigit(word.at(i)) {
countNumbers++;
}
else {
countWords++;
}
word_start = false;
}
if (word.at(i) == '.' || word.at(i) == ',') {
word_start = true;
}
}
return;
}