C++ C++;I/O don';我不明白为什么会有-1
我只是想从文件中读取每个字符,然后在屏幕上打印出来。 为了进行测试,我尝试在打印字符之前先在控制台屏幕上打印ascii值 我试图读取的文件内容如下:C++ C++;I/O don';我不明白为什么会有-1,c++,C++,我只是想从文件中读取每个字符,然后在屏幕上打印出来。 为了进行测试,我尝试在打印字符之前先在控制台屏幕上打印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*)' assign1_2.
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*)'
assign1_2.cpp:33:20:错误:无法转换'std::string'
{aka std::basic_string}'到参数“1”的“const char*”
至“int atoi(常量字符*)”
我使用了下面的代码
#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();
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
void CountLetters(字符串文件名);
int main()
{
CountLetters(“count.txt”);
}
void CountLetters(字符串文件名)
{
cout不要在不eof()时读取。这不是一个正确的读取循环
阅读成功时阅读
int x;
while ((x = in.get()) != EOF)
{
cout << x << endl;
}
intx;
而((x=in.get())!=EOF)
{
好吧,在count.txt
中有什么?你可能实际上有一个-1
在里面!你发布的编译器错误是如何关联的?你是否一步一步地调试了该方法?查看所有变量,看看在cout count.txt中是否有“-1”包含以下内容:assign1_2.cpp:33:20:错误:无法转换'std::string'{aka std::basic_string}'到'const char*',参数'1'到'int atoi(const char*)' thanks@Martin函数返回无效。所以我认为CUT与它无关。我是C++的新手,很抱歉我不太理解你的意思。谢谢你的评论。我有个问题。很多例子似乎有EOF来结束循环。你为什么说这不是一个合适的方式?thanks@user1047092:你提到的这些例子是什么?万维网上有很多例子(还有一些书!)简单的说废话。看看这里的堆栈溢出,C++的例子不错。@ USE1047092我添加了一个解释。很不幸的是,你可以发现很多例子都是错误的。我真的不明白为什么人们坚持这样的循环。对于有见地的解释,我从不知道有很多例子是错误的。