2015-07-11 60 views
-2

我不知道爲什麼ios::right工作一次。完全沒有ios :: right只能工作一次C++

同樣的問題ios::hexios::decimal和其他幾個人,除非我做一些瘋狂的代碼,並讓他們奇蹟般地重新工作

#include <iostream> 
#include <iomanip> 

using std::cout; 
using std::ios; 

int main() { 
    int len; 
    std::cin >> len; 
    // w = len + 1; 
    cout.width(len); 
    cout.setf(ios::right); 
    for (int s = 0; s < len; s++) { 
     for (int c = 0; c <= s; c++) { 
      cout << '#'; 
     } 
     cout << '\n'; 
    } 
    std::cin.get(); 
    std::cin.get(); 
} 

預期輸出:

 # 
    ## 
    ### 
    #### 
##### 
###### 

我得到什麼:

 # 
## 
### 
#### 
##### 
###### 

試過這個:

cout << ios::right << '#'; 

沒有工作。

+1

請從這個問題中刪除'ios'標籤...每個標籤都有一個描述,它解釋了何時應該使用它,這完全是'ios'標籤的主題 – Michael

+0

@Michael:已刪除。 –

回答

0

您需要在第一個循環內編寫cout.width(len-s);cout.setf(ios::right);,因爲ios :: right只能工作一次。所以它應該是

#include <iostream> 
#include <iomanip> 

using std::cout; 
using std::ios; 
int main() 
{ 
    int len; 
    cin >> len; 
    for (int s = 0; s < len; s++) 
    { 
    cout.width(len); 
    cout.setf(ios::right); 
    for (int c = 0; c <= s; c++) 
    { 
     cout<<"#"; 
    } 
    cout<<"\n"; 
    } 
    std::cin.get(); 
    std::cin.get(); 
} 

但按你所需的輸出你的代碼是不正確的,正確的代碼是:

#include <iostream> 
#include <iomanip> 

using std::cout; 
using std::ios; 
int main() 
{ 
    int len; 
    cin >> len; 
    for (int s = 0; s < len; s++) 
    { 
    cout.width(len-s); // to align properly 
    cout.setf(ios::right); 
    for (int c = 0; c <= s; c++) 
    { 
     cout<<"#"; 
    } 
    cout<<"\n"; 
    } 
    std::cin.get(); 
    std::cin.get(); 
} 
0

這裏的問題不在於right是暫時的,但該width是暫時的,那麼下一個字符是輸出不使用給定的寬度 - 其實這是一個很好的事情,或者你的第二個行會# #,所以你可能不希望那樣!

解決方法是將width調用移動到兩個循環的外部(並且在獲得更寬和更寬的輸出時相應地重新計算寬度)。

我故意不寫你應該怎麼做,因爲你需要練習思考如何工作,而不是練習CTRL-C/CTRL-V

0

做你想要什麼的更短和更簡單的方法

#include <iostream> 
using namespace std; 

int main() { 
    int n; 
    cin >> n; 
    for (int i = 1; i <= n; ++i) { 
     for (int j = n; j > 0; --j) 
      cout << (i >= j ? "#" : " "); 
     cout << endl; 
    } 
    return 0; 
} 

輸入

6 

輸出

 # 
    ## 
    ### 
    #### 
##### 
###### 

http://ideone.com/fbrfpe演示。