阅读','和'。 ' 作为 .txt 文件中的空格

Reading ' , ' and ' . ' as spaces in a .txt file

我需要帮助读取 .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;
}

这是您新修改的问题的解决方案。我采用的方法是遍历每个字符串并计算数字或单词,同时考虑到句点和逗号应被视为空格。与您的 一样,我假设给定的单词 不能 由字母或数字的组合组成。换句话说,如果第一个字符是一个数字,那么整个单词都是一个数字,否则就是一个字符单词。

#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;
}

您可以阅读所有行并逐个字符地遍历它,而不是逐字阅读。因此,当您找到空格、点或逗号时,您可以检查它是单词还是数字。

因此,您可以使用函数 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 是否不同于“\r”或“\n”。另一种选择是检查 currentChar 是否既不是字母也不是数字。

另外,记得看完后关闭文件。