2016-02-21 72 views
0
#include <stdafx.h> 
#include <string> 
#include <iostream> 

這種打印出的數「零」,即使我特地增計數,當我到達字符串中所需的字符。計劃將不會遞增計數變量

using namespace std; 

int main() 
{ 
    string userString = "I would like you to stop your chatting right now!"; 
    char userChar = 'o'; 

    int count = 0; 

    int i = 0; 

    for (i = 0; i < userString.length(); i++); 
    { 
     if (userString[i] == userChar) 
     { 
      count = count + 1; 
     } 
    } 

    cout << "There are a total of " << count << " " << userChar << "'s." << endl; 

    int rnd; cin >> rnd; 
    return 11; 
} 
+1

爲什麼您的'main'函數返回11?有效值通常是EXIT_SUCCESS和EXIT_FAILURE。 –

+6

錯字:刪除'for'行末尾的分號。 –

+0

如果您在調試器中單步執行程序,您將會注意到錯字。 –

回答

4

卸下;在for (i = 0; i < userString.length(); i++);

你永遠不循環的結束在你的代碼

2

這是正確的代碼。您在for循環的末尾添加了分號

#include <string> 
#include <iostream> 

using namespace std; 

int main() 
{ 
    string userString = "I would like you to stop your chatting right now!"; 
    char userChar = 'o'; 

    int count = 0; 

    int i = 0; 

    for (i = 0; i < userString.length(); i++) 
    { 
     cout <<userString.length(); 

     if (userString[i] == userChar) 
     { 
      count = count + 1; 
     } 
    } 

    cout << "There are a total of " << count << " " << userChar << "'s." << endl; 

    int rnd; cin >> rnd; 
    return 11; 
}