Solving Confusion about Scanf Homework

  • Thread starter Thread starter Peter P.
  • Start date Start date
  • Tags Tags
    Confusion
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
Peter P.
Messages
23
Reaction score
0

Homework Statement


The problem that was given was to prompt the user to type words with no spaces in between, and end it by pressing enter. From there, the program would calculate which letter comes the latest in the alphabet and is included in what the user types in.

example.
user types in: ABCDcduUlkO<enter>

program determines that 'u' appears latest in the alphabet based on ASCII values (also if there are either a capitalized or minimized version of a letter, they will be treated as having the same value, but the first one that appears will be displayed).

Homework Equations





The Attempt at a Solution


The problem that i am having is only with the input part, scanf. we are forced to used things we only learned in the lectures or up to a certain point in the textbook. normally i would use arrays to do this, but we didn't get that far yet.
so i know that scanf takes in the first character that is pressed only when you ask for input on a type char variable. is there any way around this or even for the program to do calculations after each keypress until they press enter?
 
Physics news on Phys.org
I would do this by putting the call to scanf inside a while loop. After a character is read from input, determine whether it is a lower-case letter. If so, subtract 32 from it to get its upper-case version. (There is also a toupper() functon that you can use - its prototype is in ctype.h.)
If the character's ASCII value is larger than 64, the ASCII value for the character just before 'A' (65), this character is the new candidate for being latest in the alphabet, so store it in some variable that keeps track of the highest letter.

Loop through all of the letters in the input string. Once the letter read is the newline character '\n', exit the loop.

It would also be a good idea to check that the current letter is actually in the alphbet. The isalpha() function can be used for this. It's also in the ctype.h header.