2017-07-18 102 views
-6

這是我的代碼,我只得到零,請幫我理解爲什麼?我想計算兩個單詞之間的空白或差距?

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

int main() 
{ 

    string a=""; 
    cin>>a; 
    int m=a.length(),count=0; 

    for(int i=0;i<m;i++) 
    { 
     if(a[i] == ' ' || a[i] == '\t' || a[i] == '\n') 
     { 
      count++; 
     } 

    } 
    cout<<count; 
    return 0; 
} 

爲什麼我會變成0?

+2

什麼是你輸入到'了'? – meowgoesthedog

+2

'std :: isspace'可能會有幫助,而不是檢查每個可能的空白字符。 – Rakete1111

+3

'cin >> a'只會讓你一個字,而不是整個字符串。查看如何從用戶獲取整個字符串('getline()') –

回答

3

當你閱讀與>>串讀取空白分隔話。總之,你不能用它來閱讀多個單詞的句子。我建議你改用std::getline

1

你正在輸入錯誤,試試這個把輸入(它將包含ofcourse空格)

的std ::函數getline(給std :: cin,一);

你的代碼的其他部分工作正常。

1

根據The manual當你使用>>接受輸入它跳過任何前導空格。

因此,您在單詞前輸入的任何空格都會丟失,並且不會放入您的字符串中。

嘗試std::getline

std::getline(std::cin, a); // reads in spaces too