编写一个程序来计算以'。'结尾的文本文件中的行数。

时间:2016-06-14 08:58:54

标签: c++ turbo-c++

#include<iostream.h>
 #include<fstream.h>
int main()
{
    ifstream infile("text.txt");
    char ch[50];
    int count=0,i;
    for(i=0;infile.eof()==0;i++)
    {
        infile.getline(ch,50);
        if(ch[i]=='\n')
            if(ch[i-1]=='.')
                count++;
    }
    cout<<"Total number of lines are:"<<count;
}

我尝试了这段代码,但它似乎无法工作。我使用逻辑来获取ch中的所有文件内容,然后检查换行符和&#39;。&#39;
      我该如何使它发挥作用 请帮忙?

编辑新代码

#include<iostream.h>
#include<fstream.h>
int main()
{
    ifstream infile("text.txt");
    char ch[50];
    int count=0,i;
    while(!infile.eof())
    {

        infile.getline(ch,50);
        for(i=1;ch[i]!='\n';i++);
        if(ch[i-1]=='.')
                count++;    

    }
    cout<<"Total number of lines are:"<<count;
}

3 个答案:

答案 0 :(得分:0)

  1. 你有长队问题
  2. 你有&#39; \ r&#39;在Windows上
  3. 你没有正确地看到行尾。
  4. 在最后一行中,您可能没有&#39; \ n&#39;
  5. 查看此解决方案:

    #include <stdlib.h>
    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    int main()
    {
        ifstream infile("text.txt");
        string str;
        int count=0;
        while(std::getline(infile,str))
        {
            string::reverse_iterator it=str.rbegin();
            while(it != str.rend() && iswspace(*it)) it++;
            if(*it =='.') count++;
        }
        cout<<"Total number of lines are:"<<count;
        return 0;
    }
    

答案 1 :(得分:0)

如果任何行超过50个字符(如果文件较长则原始版本未定义),您的程序是未定义的,您的文件结束测试是错误的,并且最后一行不一定以换行。

你可能会写这样的东西。

int main()
{
    ifstream infile("text.txt");
    std::string line;
    int count = 0;
    while (infile.getline(line))
    {
        if (line.back() == '.')
        {
            count += 1;
        }
    }
    cout << "Total number of lines are:" << count;
}

答案 2 :(得分:0)

由于您已提到50作为最大行大小。我试着根据这个假设编写代码

int main()
{
    ifstream infile("text.txt");
    char str[50]; int strSize = 50;
    int count = 0;

    while (infile.getline(str, strSize, '.')) {
        count++;
    }

    cout << "Total number of lines are:" << count << endl;

    infile.close();
    return 0;
}

此代码基本上根据&#39;的数量计算行数。&#39;在一行中出现,句子是否在新行中。