2017-03-06 180 views
-2

我試圖計算文本文件中不同字符的位置,但是我遇到了麻煩。目標是讀取文件,識別每個大/小寫字母的每個第一個實例的位置和數字的第一個實例(0-9),其中空白計數作爲對字符位置的影響。我正在用一個功能來做這件事,但已經碰壁了。 我硬編碼的一些東西主要是爲了測試/參考的目的。 使用下面的代碼只輸出「S」,沒有位置數量(以字符串形式輸出)。 我假設主要錯誤必須來自錯誤地讀取文件。我試圖一次讀完所有內容,然後解析它,看看我要測試的字符是否匹配。如何確定文本文件中字符的位置(C++)

下面的代碼:

//function 


string position_upper_alpha(char upper_letter){ 
    string line; 
    int location=0; 
    string val; 
    string iname; 
    iname = "testing.txt"; 
    ifstream ist {iname};  // ist is an input stream for the file named name 
    if (!ist) error("can't open input file ",iname); 
    getline (ist, line); 
    for (int i=1;i<line.length();i++){ 
    if (line.at(i)==upper_letter){ 
     location=i; 
     break; 
    } 
} 
    if(location ==0){ 
     val="Not Found"; 
} 
    return val; 
} 



int main(){ 

//arbitrary character for testing 
char test = 'S'; 
cout<<test<<position_upper_alpha(test); 

} 
+2

當您返回空字符串時,您會發生什麼? – mpiatek

回答

0

,因爲你正在閱讀的行的文本行,使用僅對應於行,而不是整個文件的索引比較行的字符您的邏輯是有缺陷的。

我建議將返回值更改爲帶符號整型,以便在找到字符時返回-1,並在找到該字符時查找該字符的索引。

long position_upper_alpha(char upper_letter) 
{ 
    string iname = "testing.txt"; 
    ifstream ist {iname}; 
    if (!ist) error("can't open input file ",iname); 

    int c; 
    long location = 0; 
    for (; (c = ist.get()) != EOF; ++location) 
    { 
     if (c == upper_letter) 
     { 
     return location; 
     } 
    } 

    return -1; 
} 
+0

一些跟進: 我試圖輸出位置,或者如果文件中不存在字符,則顯示「未找到」。我不能讓函數返回一個「字符串」類型的值嗎? – ztalira

+0

你可以測試'if(position_upper_alpha(something)== -1)'並輸出你想要的東西:)。此外,您可以編輯由R Sahu編寫的函數在內部進行測試並返回一個「字符串」。 – mpiatek

+0

@ztalira _「一些隨訪」_ [如何幫助vamirism?](http://meta.stackoverflow.com/questions/258206/what-is-a-help-vampire) –

相關問題