简体   繁体   中英

Program exiting when using String.ToUpper(); on a string that has spaces in it

Let me start off saying that I'm new to C#.

I'm currently in the making of my first command-line application that in it's current state can do two things. One of them is a calculator, for which I need more learning to actually make it work, and the other is a string capitalizer.

I have a string nameCapInput = Console.Readline() that takes in the user input, which then gets analyzed to make sure that no digits are allowed:

using System;
using System.Linq;

namespace First_Console_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("My first ever console application - 2020/2/26\n\n\n");
        programSel:
            Console.WriteLine("What do you want to do?\n");
            Console.WriteLine("1. Calculate Numbers \n2. Capitalize Letters/Strings");
            Console.WriteLine("Input your desired action:");
            var inputVar = Console.ReadLine();
            switch (inputVar)
            {
                case "1":
                    //Calculator code goes here
                    Console.WriteLine("Number 1 succeeded, opening calculator... Stand by");
                    Console.WriteLine("Calulator Loaded.");
                    Console.WriteLine("Doesn't work right now. Type \"exit\" to get back to the \"what do you want to do\" page.");
                    //Code goes here when I have learned the proper methods
                calcInput:
                    var calcInput = Console.ReadLine();
                    if (calcInput == "exit")
                    {
                        goto programSel;
                    } else
                    {
                        Console.WriteLine("Unknown command. Type \"exit\" to get back to the \"what do you want to do\" page.");
                        goto calcInput;
                    }
                case "2":
                    Console.WriteLine("Loading string capitalizer...");
                    Console.WriteLine("Type any string made of letters only without spaces, because if you use spaces, the program will exit. The output will make them all uppercase. Type \"exit\" to get back to the \"what do you want to do\" page.");
                inputCap:
                    string nameCapInput = Console.ReadLine();
                    bool containsInt = nameCapInput.Any(char.IsDigit);
                    bool isMadeOfLettersOnly = nameCapInput.All(char.IsLetter);
                    if (nameCapInput == "exit")
                    {
                        goto programSel;
                    }
                    else if (containsInt)
                    {
                        Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
                        goto inputCap;
                    }
                    else if (isMadeOfLettersOnly)
                    {
                        string upper = nameCapInput.ToUpper();
                        Console.WriteLine($"The uppercase version of your entered text is: {upper}");
                        goto inputCap;
                    }
                    break;
                    }
            }
        }
}

Now, everything works fine and it capializes everything I put into it except strings with spaces in them. When I type in a string with spaces in it, the program just exits with code 0. I'm not very good at C# yet, so I don't really know where to go from here. Any help is appreciated.

Every time I learn something new in C#, I try to implement it into my projects, so I can actually learn how to implement it to know when and how to use what I learned. This is an example for that.

EDIT: Added the rest of the code. Thank you all very much. There's two things I have learned here:

  1. goto is a bad habit
  2. I absolutely need to start learning to debug my own code.

Check the documentation: https://docs.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8

Based on the documentation of the IsLetter function, the space is not included in the return true cases.

I would suggest that you use regular expressions for this or change your last case to

else if (!containsInt)
{
    var upper = nameCapInput.ToUpper();
    Console.WriteLine($"The uppercase version of your entered text is: {upper}");
    goto inputCap;
}

Also check the documentation of goto: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

The goto statement transfers the program control directly to a labeled statement.

A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.

The goto statement is also useful to get out of deeply nested loops.

You are not in any such case, so you shouldn't use it.

The crux of your problem is that you are only checking if the input contains letters (not spaces). An easy fix is to change your LINQ a bit.

bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));

So now input with letters or spaces will be considered valid.

In addition, your use of goto is a very bad idea. Generally there should never be any reason to use goto .

To fix this, use a while loop and a method:

public static void Main()
{
    bool exit = false;
    do {
        exit = ProcessInput();
    }
    while(!exit);
}

private static bool ProcessInput()
{
    string nameCapInput = Console.ReadLine();

    bool containsInt = nameCapInput.Any(char.IsDigit);
    bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));

    if (nameCapInput.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
    {
        return true; //exiting so return true
    }
    else if (containsInt)
    {
        Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
    }
    else if (isMadeOfLettersOnly)
    {
        string upper = nameCapInput.ToUpper();
        Console.WriteLine("The uppercase version of your entered text is: {0}", upper);
    }   
    return false; //no exit, so return false
}

This is just a quick refactor, you could make it better.

Fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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