注册 登录
编程论坛 C++教室

统计字符数量为什么总是多一个

dtxwz 发布于 2018-08-02 22:37, 1099 次点击
// 3.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cstring>
#include<vector>
#include<array>
#include<ctime>
#include<fstream>
#include<cstdlib>
#include<cctype>
using namespace std;
const int strsize = 20;
struct intribute
{
    string name;
    double money;
};
int main()
{
    char ch;
    int count = 0;
    ifstream inFile;
    inFile.open("name.txt");
    while (inFile.good())
    {        

        inFile >> ch;        
        if (isalpha(ch))
            count++;

    }
    cout << count << endl;
    return 0;
}

name.txt
abcde
1 回复
#2
rjsp2018-08-03 08:50
while (inFile.good())
    {      

        inFile >> ch;   
当 inFile.good() 成功,就确定 inFile >> ch 能读取成功???

程序代码:
#include <iostream>
#include <fstream>
using namespace std;

int main( void )
{
    size_t count = 0;

    ifstream infile( "name.txt");
    for( char ch; infile>>ch; )
    {
        if( isalpha(ch) )
            count += 1;
    }

    cout << count << endl;
}
或者
程序代码:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;

int main( void )
{
    ifstream infile( "name.txt");
    size_t count = count_if( std::istream_iterator<char>(infile), std::istream_iterator<char>(), isalpha );
    cout << count << endl;
}


  
1