通过一系列youtube教程启动C ++,我试着在网上看,但我不知道用什么词汇来解释我的问题。我正在测试指针,我制作了这个文件,它基本上从用户那里获取用户名并再次说出来,但我不知道如何在另一个代码块中重用用户名。
// Testing Pointerds.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// This program just takes someones username and says it again.
// I get the name in void intro(), but how do I use the same string in another code block function?
// If I need to use it in 'void reuse()' how do I use the same name they type in in 'void intro()'?
void start()
{
cout << "What would you like to be called?"<<endl;
}
void usernameGet(string *a)
{
getline(cin,*a);
}
void intro()
{
string username;
start();
usernameGet(&username);
cout << "Welcome " << username << endl; // it has the username here but I want to use it in the next code block
cin.get();
}
void reuse()
{
// how do I use the same name in intro in this one?
}
int main()
{
intro();
reuse();
}
答案 0 :(得分:1)
通过传递变量,即return
来自首次初始化的地方,并将其作为参数传递给下一个需要的地方。这样你就可以避免全局状态,这很好。
答案 1 :(得分:1)
您必须传递或返回值,例如:
std::string intro()
{
std::string username;
start();
usernameGet(&username);
std::cout << "Welcome " << username << std::endl;
std::cin.get();
return username;
}
void reuse(const std::string& name)
{
// Reuse name
}
int main()
{
std::string username = intro();
reuse(username);
}