使用我的循环在C ++中的标准输入

时间:2015-07-02 11:30:41

标签: c++ iostream

#include <iostream>
#include <string>
using namespace std;

int main() {
   char c;
   cout << "enter the word.";
   cin >>  c;
   int count =0;

    while (c !='.') {
       if (c == 'b') count = count + 1;
       cin >> c;
   }

    cout << count << endl;
    return 0;
}; 

当我编译代码时,它接受单词但在此之后,不计算计数。

例如:

./d6
enter the wordbanana

然后我什么也没得到,我加了更多的话,为什么?

3 个答案:

答案 0 :(得分:2)

您的代码工作正常 问题可能出在输入字符串中。如果您在末尾输入了一些没有'.'字符的字符串,那么您的代码将以无限循环结束。并且它不会打印count变量。

return 0放置在适当的位置。

答案 1 :(得分:2)

您需要包含一个&#34;。&#34;字符以结束循环。 返回0;似乎应该在哪里,除非你不使用标准C ++。

答案 2 :(得分:1)

逻辑上正确的替代

    <receiver
        android:name = "com.mixpanel.android.mpmetrics.GCMReceiver"
        android:permission = "com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name = "com.google.android.c2dm.intent.RECEIVE"/>
            <action android:name = "com.google.android.c2dm.intent.REGISTRATION"/>

            <category android:name = "${applicationId}"/>
        </intent-filter>
    </receiver>

<强>输入

#include <bits/stdc++.h>
using namespace std;

int main() {
    string line;
    getline(cin, line);
    size_t ans, dot = line.find_first_of('.');
    if (dot != string::npos)
        ans = count(line.begin(), line.begin() + dot, 'b');
    else
        ans = count(line.begin(), line.end(), 'b');
    cout << ans << endl;
    return 0;
}

<强>输出

banana

请参阅http://ideone.com/j7b5x4演示