首页 > 解决方案 > 我不明白如何在 .txt 文件字符串输入中使用 toupper 和 isalpha

问题描述

我的程序在很大程度上是不完整的,但我认为使用 toupper 修改从文本文件输入的字符串可以将所述字符串的所有字符更改为大写。我读到它适用于 int 类型,或者在这种情况下我认为是 Ascii。但我不确定从这里去哪里。就初学者 C++ 而言,从文本文件转换和检查字符串的最有效方法是什么?

我搜索了这个问题并找到了多种方法,例如使用 std::transform,但我觉得我的导师只希望我们使用 Tony Gaddis 的《从 C++ 开始》一书中教授的方法。不幸的是,我没有在我的书中找到任何关于 toupper 用于文本文件输入的参考,仅用于 char 值。为了教育起见,我希望你知道我应该在这里使用什么以及为什么。欢迎推荐阅读。

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    string text;
    ifstream textFile;
    int ch;
    textFile.open("letter_count.txt", ios::in);
    toupper(textFile.get());
    isalpha(textFile.get());

    if (textFile)
    {
        // Read an item from the file.
        getline(textFile, text);

        // While the last read operation
        // was successful, continue.
        while (textFile)
        {
            if (textFile)
            // Display the last item read.
            cout << text << endl;

            // Read the next item.
            getline(textFile, text);
        }

        // Close the file.
        textFile.close();
    }
    else
    {
        cout << "ERROR: Cannot open file. \n";
    }
    cout << "The most common letter is " " with " " occurances. \n";
    cout << "The least common letter is " " with " " occurances. \n";


    system("pause");
}

使用 toupper 没有任何结果。

标签: c++

解决方案


那是因为 toupper 只取一个 int 值。注意这里: http ://www.cplusplus.com/reference/cctype/toupper/?kw=toupper

您必须遍历字符串中的每个字符才能进行转换。


推荐阅读