【问题标题】:Why is this returning an address in the console?为什么这会在控制台中返回地址?
【发布时间】:2013-11-28 22:50:22
【问题描述】:

我正试图围绕 ostringstreams 和 istringstreams。所以,像往常一样,我用它制作了一个登录程序。但是每次我尝试计算用户名和密码变量的内容时,它都会返回地址!

程序目的:使用输入和输出字符串流创建模拟登录屏幕

代码:

#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 == "graywolfmedia25@gmail.com" && password == "deadbeefcoffee10031995"){
    cout << endl << "username: " << *username << endl << "password: " << *password << endl;
//} else {
    //cout << endl << "ACCESS DENIED" << endl;
//}



return 0;
}

我最后尝试使用 *uptr 和 *pptr,但在此之前我尝试直接从变量中写入和读取。

【问题讨论】:

  • 我不知道你在做什么,但试试username.str()
  • @BryanChen 你是一个美丽的人 XD 谢谢你的帮助。对不起,不清楚的代码..我正在研究它:P 你能解释一下 .str() 类吗?或将我链接到一个好的资源?

标签: c++ ostringstream istringstream sstream


【解决方案1】:

您应该使用strostringstream 获取std::string

所以

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

【讨论】:

    【解决方案2】:

    标准流具有地址的输出运算符:当您尝试打印指针时,它只会打印指针的地址。此外,流有一个指针转换,用于指示流是否处于良好状态:当它处于良好状态时,即stream.fail() == false,它转换为合适的非空指针,通常只是@987654322 @。当它处于故障状态时,它返回0(它没有转换为bool的原因是为了避免,例如,std::cout &gt;&gt; i是有效的:如果它会转换为bool这个代码将是有效的) .

    假设您要打印字符串流的内容,您只需使用stream.str() 来获取流的std::string

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 2013-08-09
      • 2015-08-18
      • 2020-01-07
      相关资源
      最近更新 更多