简体   繁体   English

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

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

I am simply trying to read each character from a file and print them in the screen. 我只是想从文件中读取每个字符并在屏幕上打印它们。 For testing, I tried to print ascii value in a console screen first before printing characters. 为了测试,我尝试在打印字符之前首先在控制台屏幕上打印ascii值。

the content of the file I am trying to read is below: 我试图阅读的文件内容如下:

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*)'

I used the code below 我使用下面的代码

#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();

}

After running these code and I see "-1" at the end in the console screen. 运行这些代码后,我在控制台屏幕的末尾看到“-1”。 Anyone please explain? 有人请解释一下? thanks 谢谢

Do not read while not eof() 1 . 不读取而不是eof() 1 That's not a proper reading loop. 那不是一个合适的阅读循环。

Read while reading succeeds . 阅读成功后阅读

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

Testing for in.eof() will not guarantee reading will succeed. in.eof()测试不能保证读取成功。 When you test for in.eof() you're actually testing if the previous read operation tried to read past the end of the file . 当您测试in.eof()您实际上正在测试先前的读取操作是否尝试读取文件的末尾 This is bad, because it means the previous read operation failed . 这很糟糕,因为这意味着先前的读取操作失败 It failed and you didn't care, and just pressed on to use the value it returned even though it failed . 它失败了,你不在乎,只是按下它就会使用它返回的值, 即使它失败了

When in.get() fails, it returns the constant EOF . in.get()失败时,它返回常量EOF That's what you should be checking. 那是你应该检查的。 If in.get() fails, you don't want to continue with your loop as if it succeeded. 如果in.get()失败,您不希望继续循环,就像它成功一样。


1 Same goes for while good() or while not bad() . 1 同样适用于good()或不bad()

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

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