Solved

Switch problem in C

Posted on 2003-10-26
12
820 Views
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')
                {
      *str1++;
      count++;
      }            
return count;
}

      

int main()
{
            char string1[100];
      int choice = 0;
      
      printf("\n\nPlease Enter a String: ");      
      scanf("%s",string1);                  
                printf("\nMENU");
      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:");
      scanf("%d",&choice);


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

      default:
      {      printf("illegal selection");
                break;
                }
      }


        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"

thanks
Simon
0
Comment
Question by:simonsng
  • 3
  • 3
  • 2
  • +3
12 Comments
 
LVL 15

Expert Comment

by:jimmack
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) ;-)
0
 

Author Comment

by:simonsng
ID: 9623034
jimmack,

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  
0
 
LVL 1

Accepted Solution

by:
logicTRANCE earned 100 total points
ID: 9623094
Hi!

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();

i.e.,
     gets(string1);

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!

Goodluck!
Happy Programming!
0
 
LVL 8

Expert Comment

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

Expert Comment

by:logicTRANCE
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.

Thanks!
Happy Programming!
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 8

Expert Comment

by:shamstar
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??
0
 

Author Comment

by:simonsng
ID: 9624049
logictrance,

my apology, didn't realise it till I submitted.. is there anyway to change the grade?
0
 
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.
bye
0
 
LVL 1

Expert Comment

by:logicTRANCE
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!
0
 
LVL 8

Expert Comment

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

Expert Comment

by:jetstream
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).
Cheers.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
for loop with Set 4 46
Using YubiKey with REST API application 2 82
noX challenge 17 76
Not needed 13 57
This article will show, step by step, how to integrate R code into a R Sweave document
This is an explanation of a simple data model to help parse a JSON feed
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
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…

760 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now