繁体   English   中英

C ++ I / O不明白为什么有-1

[英]C++ I/O don't understand why there is -1

我只是想从文件中读取每个字符并在屏幕上打印它们。 为了测试,我尝试在打印字符之前首先在控制台屏幕上打印ascii值。

我试图阅读的文件内容如下:

assign1_2.cpp:33:20: error: cannot convert 'std::string 
    {aka std::basic_string<char>}' to 'const char*' for argument '1' 
    to 'int atoi(const char*)'

我使用下面的代码

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;

void CountLetters(string filename);

int main()
{
        CountLetters("count.txt");
}

void CountLetters(string filename)
{
    cout << filename << endl;

    ifstream in;
    in.open(filename.c_str(), ios::in);
    vector<char> letter;
    char temp;
    while (!in.eof())
    {
        cout << in.get() << endl;
    }

    in.close();

}

运行这些代码后,我在控制台屏幕的末尾看到“-1”。 有人请解释一下? 谢谢

不读取而不是eof() 1 那不是一个合适的阅读循环。

阅读成功后阅读

int x;
while ((x = in.get()) != EOF)
{
    cout << x << endl;
}

in.eof()测试不能保证读取成功。 当您测试in.eof()您实际上正在测试先前的读取操作是否尝试读取文件的末尾 这很糟糕,因为这意味着先前的读取操作失败 它失败了,你不在乎,只是按下它就会使用它返回的值, 即使它失败了

in.get()失败时,它返回常量EOF 那是你应该检查的。 如果in.get()失败,您不希望继续循环,就像它成功一样。


1 同样适用于good()或不bad()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM