2016-06-14 84 views
-3
#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中的所有文件內容,然後檢查換行符和'。'
如何讓它工作。
請幫忙?編寫一個程序來計算以'。'結尾的文本文件的行數

編輯新代碼

#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; 
} 
+0

添加一些調試到你的循環來看看你在讀什麼,你的索引變量等... – Nim

+0

@Nim我試過了,我猜測循環沒有正常運行 – user3500780

+0

不要猜測,試圖瞭解什麼是發生在那個變量,以及'getline()'在做什麼... – Nim

回答

0
  1. 你有問題,排長
  2. 你有「\ r」在Windows
  3. 你是不是在一行的末尾正確看問題。
  4. 在最後一行
  5. 你可能沒有「\ n」

退房這一解決方案:

#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; 
} 
+0

由於在文本模式下打開文件,因此Windows上的換行符沒有問題。 – molbdnilo

+0

我試過這個程序,它計算所有行,不管是否以'。'結尾。 – user3500780

+0

@ user3500780它修復了。 – SHR

0

如有線長超過五十個字符你的程序是不確定的(原始版本是未定義如果文件更長),您的文件結束測試是錯誤的,並且最後一行不一定以換行符結束。

你可能會這樣寫。

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; 
} 
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; 
} 

這段代碼基本上是根據'。'的數量來計算行數。呈現在一行中,句子是否在新行中。

相關問題