我試圖計算文本文件中不同字符的位置,但是我遇到了麻煩。目標是讀取文件,識別每個大/小寫字母的每個第一個實例的位置和數字的第一個實例(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);
}
當您返回空字符串時,您會發生什麼? – mpiatek