2013-11-28 31 views
0

我試圖圍繞ostringstreams和istringstreams來包裝我的頭。所以,正如我一直所做的那樣,我做了一個登錄程序。但每次我嘗試關閉用戶名和密碼變量的內容時,它都會返回地址!爲什麼這會在控制檯中返回一個地址?

用途的程序:使用的輸入和輸出stringstreams

創建一個模擬的登錄屏幕

代碼:

#include<iostream> 
#include<string> 
#include<conio.h> 
#include<stdio.h> 
#include<sstream> 

using namespace std; 

int main(int argv, char *argc[]){ 

char ch; 
ostringstream username, 
    password; 
ostringstream *uptr, 
    *pptr; 

uptr = &username; 
pptr = &password; 

cout << "Welcome" << endl << endl; 

cout << "Enter a username: "; 
do{ 

    ch = _getch(); 
    *uptr << ch; 
    cout << ch; 

}while(ch != '\r'); 


cout << endl << "Enter a Password: "; 
do{ 
    ch = _getch(); 
    *pptr << ch; 
    cout << "*"; 

}while(ch != '\r'); 

//if(username == "[email protected]" && password == "deadbeefcoffee10031995"){ 
    cout << endl << "username: " << *username << endl << "password: " << *password << endl; 
//} else { 
    //cout << endl << "ACCESS DENIED" << endl; 
//} 



return 0; 
} 

我使用* uptr和* PPTR上次嘗試,但在此之前,我試圖只需從變量中直接寫入和讀取即可。

+1

我不知道你在做什麼得到std::string,但儘量'username.str()' –

+0

@BryanChen你是一個美麗的人XD感謝您的幫助。並抱歉不清楚的代碼..我正在努力:P你能解釋.str()類嗎?或者將我連接到一個好的資源,將? –

回答

2

你應該使用strostringstream

所以

cout << endl << "username: " << username.str() << endl << "password: " << password.str() << endl; 
1

標準流具有地址的輸出操作符:當您嘗試打印指針時,它只會打印指針的地址。另外,這些流具有到指針的轉換,該指針用於指示流是否處於良好狀態:當它處於良好狀態,即stream.fail() == false時,它轉換爲合適的非空指針,通常只是this。當它處於故障狀態時,它將返回0(它不轉換爲bool的原因是爲了避免例如std::cout >> i有效:如果它將轉換爲bool此代碼將是有效的)。

假設您要打印字符串流的內容,您只需使用stream.str()即可獲取流的std::string

+0

非常感謝你@DietmarKuhl!這有幫助。 –

相關問題