C++ 在不同的if语句中如何更改变量?(C+;+;)
我正在制作一个程序,你输入一些东西,它会检测到。然后它改变一个变量。但问题是我需要访问if语句之外的新变量内容。代码如下:C++ 在不同的if语句中如何更改变量?(C+;+;),c++,scope,C++,Scope,我正在制作一个程序,你输入一些东西,它会检测到。然后它改变一个变量。但问题是我需要访问if语句之外的新变量内容。代码如下: #include "stdafx.h" #include <string> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main() { while (1) {
#include "stdafx.h"
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
while (1)
{
string dir = "C:/";
string line;
string afterPrint;
string prompt = "| " + dir + " |> ";
cout << prompt;
getline(cin, line);
stringstream ss(line);
while (ss)
{
string command;
ss >> command;
transform(command.begin(), command.end(), command.begin(), ::tolower);// Command, but lowercase
if (command == "cd")
{
string dir;
if (ss >> dir)
{
cout << "Directory: " << dir << "\n"; // it changes here
string prompt = "| " + dir + " |> "; // and here
}
}
else if (command == "c:" || command == "c:\\")
{
cout << "Directory: " << dir << "\n";
}
else
{
cout << "error\n";
}
break;
}
// but I need it here (when the loop restarts)
}
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
而(1)
{
string dir=“C:/”;
弦线;
字符串后印本;
字符串提示符=“|”+dir+“|>”;
cout>命令;
转换(command.begin(),command.end(),command.begin(),::tolower);//命令,但小写
如果(命令==“cd”)
{
字符串目录;
如果(ss>>dir)
{
cout在第二个循环上方声明命令。然后在第二个循环内部重置命令=“在放置stringstream的内容之前只需在循环外部声明变量:
std::string dir;
while (ss)
{
...
if (ss >> dir)
{
...
}
}
//use dir here