看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《tananadishow (小賴)》之銘言: : ( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) : ( 未必需要依照此格式,文章條理清楚即可 ) : 遇到的問題:ZJ a011 : 算一算每行有幾個字(word)。 : Word的定義是連續的字元(letter: A~Z a~z)所組成的字。 : 希望得到的正確結果: : Inptu: Hello everybody!! : Output: 2 : 程式跑出來的錯誤結果: : 我的程式都會少1 : 開發平台:Dev-C++ : 有問題的code: : #include<iostream> : using namespace std; : int main() : { : string a; : while(getline(cin, a)) : { : int x=a.length(); : int y=1; : for(int i=0;i<x;i++) : if(a.substr(i,1)==" ") y++; : cout<<y<<endl; : } : return 0; : } : 補充說明: 1) 麻煩你弄一個好一點的標題, 你這個問題和 ZJ 的關係是什麼? 這和 "寫程式的問題" 沒什麼大分別 2) 這世上有一種東西叫 debugger. 你跟著 trace 一次你的 code 你就知道為什麼. 你的程式只是在算 string 裡有多少個 space. 出來的結果當然不對. 至於怎樣才是算 "字數" (no of words), 這就是你要想的東西. 不要期望大家會幫你做你該做的功課 另, 要看某個字元是不是 space, 不必用 substr, 這太浪費了 if (a[i] == ' ') 就可以了 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.238.156.189
VictorTom:推a大:) 02/25 11:59
loveme00835:可以參考cctype header, 加上iterator會更快 02/25 18:01