Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Switch problem in C

Posted on 2003-10-26
Last Modified: 2007-12-19
This is a newbie question, but I can't seem to solve the prob

here is the source

int Str_len(char str1[])
      int count=0;
      while(*str1 != '\0')
return count;


int main()
            char string1[100];
      int choice = 0;
      printf("\n\nPlease Enter a String: ");      
      printf("\n1 - Count Number of Characters in String");
      printf("\n2 - Count Number of Words in String");
      printf("\n3 - Remove spaces in String");
      printf("\n4 - Reverse String");
      printf("\n6 - Look for sub-string in String");
      printf("\n7 - Insert sub-string into String\n\n");
                printf("Please option 1 to 7:");

      switch (choice)
      case 1:
            printf("%s has %d characters",string1, Str_len(string1));

      {      printf("illegal selection");

        return 0;

My problem is that everytime I enter a string with spacings, example "C is fun", the result is 'Illegal selection' which is in the default case, But it works if the string is just 1 word without spacing, example "cow"

Question by:simonsng
  • 3
  • 3
  • 2
  • +3
LVL 15

Expert Comment

ID: 9622782
Hi Simon,

I don't think it's the spaces in the string causing the problem ;-)

I assume that the problem occurs when you enter a selection from your menu that is anything other than "1".

This is because your switch statement needs "case"s for each of the other options 2 .. 7.

Copy your "case 1:" statement to create these.  To start with, just have a printf inside each one that outputs the number of the selection you have made (don't forget to include the break statement though) ;-)

Author Comment

ID: 9623034

thats a negatory. Tried that before, but only works when i input a string without spacing, otherwise, same result. wasnt able to select as there was an immediate display of the menu and illegal selection printing out, didnt even get to input a choice for the switch  

Accepted Solution

logicTRANCE earned 100 total points
ID: 9623094

You are accepting a string from user using the
scanf("%s",string1) function. the scanf() function takes a
' '(space) as the end of string character.
So what happens when u enter a string with multiple words is that the scanf function reads the characters from the keyboard buffer until it reaches the 1st SPACE or ENTER character. It ignores the rest of the line. So actually the programme runs with the 1st word of the string.

But then the menu is displayed again and the next scanf() accepts the choice. Now, the remaining words of the previous string are still there in the keyboard buffer, which are read by the scanf() into the variable 'choice'.
Since the value of choice now doesn't match any of the choices you provided, the default case is executed.

I order to be able to accept multiword strings, use gets(char*) instead of scanf();


This function will accept input string in string1 until the enter key is not pressed.

No need for the rest of the cases to be written for this case to run!

Happy Programming!
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center


Expert Comment

ID: 9623226
How come you only awarded logicTRANCE a grade B??
It seems a perfectly good answer to me.

Expert Comment

ID: 9623272
Hi shamstar!

Thanks a lot for mentioning that!
I didn't cos i thought it would not be appropriate!

I'd be grateful if hta grade is somehow changed to an A.

Happy Programming!

Expert Comment

ID: 9623669
I know what you mean about not mentioning it yourself.
To me giving a grade of A would make sense especially since you provided a solution which only needed one line of code to be changed, and you also provided a good description of why the problem happened with the old code. (Not to mention you beat me to typing the answer :p )

Dunno if the grade can be changed afterwards, maybe Mods can do it??

Author Comment

ID: 9624049

my apology, didn't realise it till I submitted.. is there anyway to change the grade?
LVL 13

Expert Comment

by:Naman Goel
ID: 9625359
actually u can not enter multiple word string using scanf function in this way.
beacuse sacnf just get the first word.
do try out getch() or scanf("%[^~]",s)
that means it accepts all the character to string s until u enter ~ sign as terminator.

Expert Comment

ID: 9626725
hello simonsng!

I think you can make a request to CS for changing the grade. Just leave a message in the Customer Support(CS) section.
I'd be really grateful!

Shamstar, thanks for ur appreciation!

Happy Programming!

Expert Comment

ID: 9626876
Not a problem logicTRANCE.
Sending a message to CS should take care of it.

Expert Comment

ID: 9631625
Also to naman_goel's answer....   I use (sometimes)  scanf("%[^\n]",s);    which will accept until a newline (without the need for a ~ terminator).

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 82
numbers ascending pyramid 101 212
MacOS and programming in React 7 41
Tax Considerations for positive outcomes, outside the U.S. for IT Professionals 3 48
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question