題目1182:統計單詞

Problem:


Solution:

這道題的思路其實是很簡單的,但由於我對c++基本語法的不清楚導致耗費了很久。在用cin讀取輸入字符串時,遇到空白就會停止了,比如說輸入爲“hello world”讀進去的只有“hello”,只能cin<<hello<<world這樣讀。 如果我們希望最終得到的字符串中保留空白符,可以用getline()來讀取,getline函數的參數爲一個輸入流和一個string對象,從給定輸入流中讀取內容,直到遇到換行符纔會停止,如getline(cin,line)
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;

int main()
{
    string input;
    while (cin >> input )
    {
        int count = 0;
        int i;
        for (i = 0;input[i]!='\0' && input[i]!='.';i++)
        {
            count++;
        }
        if (input[i] == '.') cout<<count<<endl;
        else cout<<count<<' ';
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章