C++ 试图返回c+;的输入文件的大小+;但是,当我将char变量转换为string时,收到一个错误

C++ 试图返回c+;的输入文件的大小+;但是,当我将char变量转换为string时,收到一个错误,c++,string,file,input,count,C++,String,File,Input,Count,我正在尝试计算程序中的字符数。最初,我的变量“words”是一个字符,文件读起来很好。当试图确定变量的长度时,它不能与.length()一起使用。您能否解释一下如何将“words”变量设置为字符串,以便words.length()正确执行 第words=readFile.get()行出错是: 与“操作员!=”不匹配用“文字”=-0x00000000000000001' #include <iostream> #include <cmath> #include <fs

我正在尝试计算程序中的字符数。最初,我的变量“words”是一个字符,文件读起来很好。当试图确定变量的长度时,它不能与
.length()
一起使用。您能否解释一下如何将“words”变量设置为字符串,以便
words.length()
正确执行

words=readFile.get()行出错是:

与“操作员!=”不匹配用“文字”=-0x00000000000000001'

#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <string>
#include <stdio.h>
#include <math.h>
using namespace std;

int main() {

//buff array to hold char words in the input text file
string words;

//char words;

//read file
ifstream readFile("TextFile1.txt");
//notify user if the file didn't transfer into the system
if (!readFile)
    cout <<"I am sorry but we could not process your file."<<endl;

//read and output the file
while (readFile)
{
    words = readFile.get();
    if(words!= EOF)
      cout <<words;
}

cout << "The size of the file is: " << words.length() << " bytes. \n";

return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
//buff数组,用于在输入文本文件中保存字符
字符串;
//字符词;
//读取文件
ifstream readFile(“TextFile1.txt”);
//如果文件未传输到系统中,请通知用户
如果(!readFile)

你应该读一些参考资料。试着去寻找


我不知道你想要什么,但如果你只想数数单词,你可以这样做:

std::ifstream InFile(/*filename*/);
if(!InFile)
    // file not found

std::string s;
int numWords = 0;

while(InFile >> s)
    numWords++;

std::cout << numWords; 
第二种方法更简单: 如果文件使用,numCharacters==fileSize;
否则,如果使用,numCharacters==fileSize/2

当然,如果您只是为了计算字符数而这样做(并且打算使用std::istream::get),那么您最好这样做:

int NumChars = 0;
while (readFile.get())
{
    NumChars++;
}
哦,顺便说一句,您可能希望在处理完文件后关闭它。

get()返回一个int,要执行您正在执行的操作,您必须在附加到“words”之前检查该int,而不是根据EOF检查单词,例如:

...
//read and output the file
while (readFile)
{
    const int w = readFile.get();
    if (w!= EOF) {
      words += w;
      cout <<words;
    }
}
...
。。。
//读取并输出文件
while(readFile)
{
const int w=readFile.get();
如果(w!=EOF){
单词+=w;

您是否尝试过检查get函数的签名…例如,您是否真的需要一个字符串来计算字符数。这肯定不会按您所想的方式工作。我的意思是,即使get具有正确的签名,您也会在循环的每个输入中替换该字符串。
int NumChars = 0;
while (readFile.get())
{
    NumChars++;
}
...
//read and output the file
while (readFile)
{
    const int w = readFile.get();
    if (w!= EOF) {
      words += w;
      cout <<words;
    }
}
...