當計算一個簡單的字串時,這有效:
string x = "aabbcc";
int n = count (x.begin(), x.end(), 'a');
cout << n;
這會輸出正確的“2”。但是,當我從文本檔案中讀取字串時:
ifstream myFile;
myFile.open(argv[1]);
string x;
if (myFile.is_open()) {
while (myFile) {
x = myFile.get();
int n = count(x.begin(), x.end(), 'a');
cout << n;
這會輸出 0 和 1,1 出現在 'a' 出現的位置。相反,我想要一個總數。
提前致謝。
uj5u.com熱心網友回復:
get() 函式一次提取一個字符并將其傳遞給變數 X。
在 while 回圈的每次迭代中,X 的大小為 1。
變數 n 包含一個字符 X 中的“a”字符的計數。
因此,您的輸出是檔案的每個字符中的 a 數。 對于字符實際上是“a”的情況,您可以計算它找到了一個 a 計數。
使用這個: 簡單的選項: 將 n 更改為靜態
static int n = 0;
while (myFile) {
x = myFile.get();
n = count(x.begin(), x.end(), 'a');
}
cout<<n;
硬選項 使用不同的 get() 函式變體,為您提供整個字串。將其傳遞給字串變數 X
uj5u.com熱心網友回復:
也許是這樣的?
ifstream myFile;
myFile.open(argv[1]);
if (myFile.is_open()) {
stringstream iss;
iss << f.rdbuf();
string x = iss.str();
int n = count(x.begin(), x.end(), 'a');
cout << n;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409048.html
標籤:
上一篇:CodeLiteIDE未讀取檔案
