我正在制作一个程序,您可以在其中输入内容并进行检测。然后它改变了一个变量。但问题是我需要访问if语句之外的新变量内容。这是代码:
#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;
}
任何帮助都将受到高度赞赏! 提前谢谢!
答案 0 :(得分:1)
只需在循环外声明变量:
std::string dir;
while (ss)
{
...
if (ss >> dir)
{
...
}
}
//use dir here
答案 1 :(得分:0)
在第二个循环之上声明命令。然后在放置stringstream的内容
之前在第二个循环重置命令=“”内