Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用于计算字数的函数定义_C++_File_Count - Fatal编程技术网

C++ 用于计算字数的函数定义

C++ 用于计算字数的函数定义,c++,file,count,C++,File,Count,编写一个函数定义,计算文本源中一行的字数 我尝试了两种不同的代码,得到了两种不同的结果 countwords() { ifstream file("notes.txt"); int count=0; char B[80]; file>>B; While (!file.eof()) { cout<<B<<endl; file>>B; count++; } } countword

编写一个函数定义,计算文本源中一行的字数

我尝试了两种不同的代码,得到了两种不同的结果

 countwords()
 {
    ifstream file("notes.txt");
    int count=0;
    char B[80];
    file>>B;
  While (!file.eof())
  {
   cout<<B<<endl;
   file>>B;  
   count++;
   }
}
countwords()
{
ifstream文件(“notes.txt”);
整数计数=0;
charb[80];
文件>>B;
而(!file.eof())
{
库特布;

cout你的答案的第二个版本总是多循环一次

想想看:如果
文件>>B
失败会发生什么?您仍然会增加
计数

另外,不要循环使用
eof()
,因为循环次数通常过多。()

相反,请执行以下操作:

while(file >> B)
{
   std::cout << B << std::endl;
   ++count;
}
while(文件>>B)
{

然而,问题不在于看它的工作读数


谈到您的代码,请注意第一个代码中的
文件>>B;
。由于
文件>>B;
在最后一次执行第二个代码时失败,您得到的正确答案少了一个。

输出的字数比实际字数多1个的原因:在第二个版本中,您在第一次阅读之前输出了B。这是一种不匹配的用法序列化变量,并可能导致输出看起来像垃圾或空行的内容。不可靠的代码


另外,我建议使用std::string而不是char[80]作为变量B的类型。

不要检查
eof()
只要搜索原因,就会看到.loop on
while(file>>B)
我想后者可能也会给你一个很好的胡言乱语屏幕,因为
B
内容是不确定的,发送到
cout
调用UB。使用a而不是
char[]<代码> >没有任何方法能给出任何答案。请发布真实代码。我刚开始C++文件。请不要介意我说什么不对。但是FIL> > B怎么会失败?一旦它结束,EOF()就真的,循环会终止吗?@亚西尔:等待<代码> EFF()
要求您实际到达文件的末尾,但如果其他任何错误条件出现,该怎么办?文件不存在、读取失败或任何其他
ios\u base::failure
eof()
将继续返回
false
while(file >> B)
{
   std::cout << B << std::endl;
   ++count;
}