如何在不同的 if 语句中更改变量?(C++)

How do you change a variable while in a different if statement? (C++)

本文关键字:变量 改变 C++ 语句 if      更新时间:2023-10-16

我正在制作一个程序,您可以在其中输入某些内容并检测到它。 然后它更改一个变量。但问题是我需要访问 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 << "errorn";
                        }
                        break;
                }
                // but I need it here (when the loop restarts)
        }
    return 0;
}

任何帮助将不胜感激!提前感谢!

只需在循环外声明变量:

std::string dir;
while (ss)
{
  ...
  if (ss >> dir)
  {
    ...
  }
}
//use dir here

在第二个循环上方声明命令。然后在第二个循环中重置命令 = " 之前放置字符串流的内容