如何在不同的 if 语句中更改变量?(C++)
How do you change a variable while in a different if statement? (C++)
我正在制作一个程序,您可以在其中输入某些内容并检测到它。 然后它更改一个变量。但问题是我需要访问 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
在第二个循环上方声明命令。然后在第二个循环中重置命令 = " 之前放置字符串流的内容
相关文章:
- 变量没有改变?通过向量的函数调用
- 在向量内更改变量的值不会改变其在向量外的值
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 标准在哪里定义了可变变量可以改变
- C++11:可变的 lambda 似乎没有改变变量?
- printf() 似乎改变了一个变量
- 为什么我的变量在单独的线程中修改时没有改变?C++/boost
- 为什么 Player.x 和 Player.y 变量没有改变?
- C - 如何将各处的静态函数称为改变其私有变量
- 即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
- 为什么调用 CUDA 内核函数时这个类成员变量没有改变
- 全局变量的顺序会改变C /OpenGL的性能
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 如何在C++中改变超类和子类的变量
- 为什么变量不会改变
- 变量的范围大于for循环,为什么它不改变值
- 变量似乎在自行改变值
- 在一个case中改变switch变量
- 当赋值给变量时,数字改变值