C ++ I / O不明白为什么有-1 [英] C++ I/O don't understand why there is -1

查看:73
本文介绍了C ++ I / O不明白为什么有-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从文件中读取每个字符并将其打印在屏幕上。
对于测试,我试图在打印字符之前在控制台屏幕上打印ascii值。

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.

我想要读取的文件的内容如下:

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

$ basic_string< char>}'to'const char *'for argument' b
$ b

我使用下面的代码

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

}

运行这些代码后,我看到-1在控制台屏幕的结尾。任何人请解释一下?感谢

After running these code and I see "-1" at the end in the console screen. Anyone please explain? thanks

推荐答案

不要读时 eof() 1 。这不是一个正确的阅读循环。

Do not read while not eof()1. That's not a proper reading loop.

阅读成功时读取

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

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

Testing for in.eof() will not guarantee reading will succeed. When you test for in.eof() you're actually testing if the previous read operation tried to read past the end of the file. 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.

in.get()失败,它返回常量 EOF 。这是你应该检查。如果 in.get()失败,您不想继续循环,因为它已成功。

When in.get() fails, it returns the constant 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.

1 同样适用于 good() c> bad()

1 Same goes for while good() or while not bad().

这篇关于C ++ I / O不明白为什么有-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆