Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

scanf() and structure members

Status
Not open for further replies.

xlav

Technical User
Oct 23, 2003
223
JM
I created a structure with a member that holds a single character. The user is requested to input a single character to store in this structure member. Using - scanf("%c", &struct.member) or scanf("%c", struct.member) doesn't ascept the entered character. How can I ascept a character for a structure member?

-x
 
The user must press Enter to pass input to scanf - that's all. Of course, you must use 1st form of scanf call:
Code:
scanf("%c",&s.member); // ! struct.member, struct is keyword
You can't catch every keypress via stdin in C/C++: RTL collects them and passes to a program after Enter...
 
Thanks for your help. When I put &S.MEMBER program prints input statement, doesn't stop to receive input data, prints a following input statement and then waits for that data to be input. Removing & from S.MEMBER causes the foll. error, thread stopped C:\..... Fault: access violation at 0x404fa8: write to address 0x0. I'm entering float, int, string and a single character data for a structure to the screen and am only having difficulty with ascepting the character data in scanf.

-x
 
You can't remove address op sign & from scanf argument! You MUST present addresses of input target vars!
It's no matter if it's a member of structure or an ordinal var.
That's another matter: scanf("%c") does not eat '\n' from stdin. Try getch() after 1st scanf: it returns '\n' (dec 10). Now your stdin ready to accept next user input...
Alas, stdin user interface is not the best solution...
Simplify this interaction design. Write your own input functions to deal with that buffered chars. Make experiments etc...
Don't forget: stdin works with file input as such, not a specially console input. If I want to implement any portable and (more or less;) robust and misprint-tolerant console interface, I prefer to read a whole string (upto Enter) then process it in the memory (sscanf or some kind of ad hoc lexer/parser)...
 
> When I put &S.MEMBER program prints input statement, doesn't stop to receive input data
It's reading the newline from the end of your previous input.

Reading each line using fgets(), then doing whatever you want with the buffer in memory (extraction, validation etc) is the way to go.

scanf() has way too many traps for it to be used for serious applications.


--
 
Thanks. used a 2-element array and asceptrd a string insted of char. last element is string null termination. Will try writing input func to work with input buffer.

-x

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top