2016-02-21 32 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; 
}