我只是想从文件中读取每个字符并在屏幕上打印它们.为了测试,我尝试在打印字符之前首先在控制台屏幕上打印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*)'
Run Code Online (Sandbox Code Playgroud)
我使用下面的代码
#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();
}
Run Code Online (Sandbox Code Playgroud)
运行这些代码后,我在控制台屏幕的末尾看到"-1".有人请解释一下?谢谢
R. *_*des 14
不要读而不是eof()1.那不是一个合适的阅读循环.
阅读成功后阅读.
int x;
while ((x = in.get()) != EOF)
{
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
测试in.eof()不保证阅读会成功.当您测试时,in.eof()您实际上正在测试上一次读取操作是否尝试读取文件末尾.这很糟糕,因为这意味着先前的读取操作失败.它失败了,你不在乎,只是按下它就会使用它返回的值,即使它失败了.
如果in.get()失败,则返回常量EOF.那是你应该检查的.如果in.get()失败,您不希望继续循环,就好像它成功了.
1 同样适用于while good()或while bad().
| 归档时间: |
|
| 查看次数: |
911 次 |
| 最近记录: |