简体   繁体   English

验证用户输入并在循环内更新变量

[英]Validating User Input and updating a variable inside a loop

I'm trying to have a user enter a file path as a string (but for learning purposes I'd like to treat the path as any string variable, but I am open to suggestions for file path validation). 我试图让用户以字符串形式输入文件路径(但是出于学习目的,我希望将路径视为任何字符串变量,但是我愿意接受有关文件路径验证的建议)。 The issue I am having and cannot seem to figure out is once inFilepath is updated from Console.ReadLine(), it only will show up in the Console.WriteLine() statement that concatenates it. 我遇到的并且似乎无法解决的问题是,一旦从Console.ReadLine()更新了inFilepath,它只会在连接它的Console.WriteLine()语句中显示。 Trying to display it anywhere else displays "", which I know indicates that the variable was not updated since its assignment as "". 尝试将其显示在其他任何地方都会显示“”,我知道这表明该变量自分配为“”以来并未更新。 I believe this is a scope issue, but I am at a loss as to why, in the end I just need to access the updated inFilepath in the same scope as its declaration. 我相信这是一个范围问题,但是我无所适从,为什么最后我只需要在与声明相同的范围内访问更新的inFilepath。

string correctPath = "no";
string inFilepath = "";
bool flag = false;
bool inFlag = false;
while (!flag) {
    Console.WriteLine("Please Enter the Tour file path now...");
    inFilepath = Console.ReadLine();
    inFilepath += "\\";
    while (!inFlag) {
        Console.WriteLine("Is this the correct filepath: " + inFilepath + "  ?" +
        "\n Enter 'no' if it is incorrect or 'yes' if it is correct.");
        correctPath = Console.ReadLine();
        if (correctPath == "yes") {
            inFlag = true;
            flag = true;
        }
        else {
            break;
        }
    }
}
Console.WriteLine("path: ", inFilepath);

Your problem is here, you are passing the param arg, but not using/displaying it 您的问题在这里,您正在传递参数arg,但未使用/显示它

Console.WriteLine("path: ", inFilepath);

You need to add {0} , like 您需要添加{0} ,例如

Console.WriteLine("path: {0}", inFilepath);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM