2010-11-16 111 views
0

所以我需要像C++多行輸入

first line 
line with some number like 5 
line 3 
empty line 

什麼是從用戶獲得這樣的字符緩衝區,以及如何獲得它的長度的正確方法創建一個包含4行文本(EN_US)的字符緩衝區?

+0

這是功課?它很酷,如果它是,但我們想知道。 – 2010-11-16 22:41:14

+0

@John,我不這麼認爲,最近來自@Kabumbus的很多qs。 – 2010-11-16 22:45:56

+0

你一般都想閱讀,直到某種輸入終止,還是隻是這四條固定線? – Pyjong 2010-11-16 22:49:40

回答

2

非但沒有這樣的一個緩衝的,它可能是更容易使用getline標準輸入讀取四行成獨立string秒(如果你喜歡使用一個循環):

那麼總的數據長度爲總長度爲個人string。也可以使用此方法從用戶檢索數據,然後將它們連接成四行stringstream

組合代碼示例:

#include <string> 
#include <sstream> 
#include <iostream> 

std::string s[4]; 
size_t length(0); 

std::ostringstream output; 

for (size_t index = 0; index < 4; ++index) 
{ 
    getline(std::cin, s[index]); 
    length += s[index].length(); 

    output << s[index] << std::endl; 
} 

output.flush(); 
streamoff streamLength = output.tellp(); 
+0

不錯,但我會去一個'std :: string行[4];對於(...)std :: getline(std :: cin,lines [i]);'使它更容易改變,減少寫入的痛苦! – 2010-11-16 23:04:27

+0

@André,同意,我會改變這一點。 – 2010-11-16 23:06:27