【问题标题】:get character from stream c++从流 C++ 中获取字符
【发布时间】:2016-08-18 02:18:54
【问题描述】:
FILE *in_fp;   

 void getChar() 
     {
        if ((nextChar = getc(in_fp)) != EOF) 
        {
            if (isalpha(nextChar))
                charClass = LETTER;
            else if (isdigit(nextChar))
                charClass = DIGIT;
            else charClass = UNKNOWN;
        }
        else
            charClass = EOF;
    }

我想要 c++ 中的函数等效函数 getc() 我搜索但我没有找到

注意 如果我使用 FILE,编译器会显示此错误

source.cpp(47): error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

【问题讨论】:

    标签: c++ file stream character


    【解决方案1】:

    我假设您想使用 C++ I/O 机制打开一个文件并读取一个字符。您可以使用 I/O 流来做到这一点。

    你可以这样做:

    #include <fstream>
    ....
    std::ifstream in;//an input file stream
    char nextChar;
    
    in.open("your_file_name");//open a file for reading
    if(in)
    {//if opened successfully
        in.get(nextChar);//read a character from the stream
        .....//your other code
    }
    

    【讨论】:

    • 对不起。我没听明白,这是一个需要澄清的问题吗?
    • 代码不能正常工作,因为 'if (in_fp.get(nextChar)!=EOF)' 由于是 int,所以无法将 char 与 EOF 匹配
    • ifstream 有一个eof() 函数。你可以用它来检查文件的结尾。
    • 我使用它,但此消息错误 cpp(116):注意:尝试匹配参数列表时 '(std::basic_istream>, 重载函数)'
    • 如何在代码中使用它。顺便说一句,您可以只说if(in_fp.get(nextChar)),因为如果读取失败或可能if(nextChar=in_fp.get())!=EOF),它将返回false
    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多