We help IT Professionals succeed at work.

scanf

YamSeng
YamSeng asked
on
If I have 3 variables to scan in and the format goes like this

int char[] int
or "number word number" separated by 0 or more white space.

PS: The word in the middle must be alphabets

How can I scan them into the respective variables?  I've thought of using a for loop to scan each character by character for the word in the middle, but I feel it's so inefficient.  Is there a better way to do it?

Yam
Comment
Watch Question

Commented:
This code will do:

    int x,y;
    char str[100];
    scanf( "%d %100s %d" , &x, str,&y );

As you can see, a string can be read from the standard input using the %s formatting string. You can add a number between the percent sign and the 's' character to indicate the maximum allowed number of characters. Make this number equal to the buffer string you are using to save the string into so that the user won't be able to enter a too long value causing a buffer overflow.

Author

Commented:
No.  This didn't work.

If the string entered is say

"1+2"
x will be "1"
str will be "+2"
and y will not be assigned any value.

I need it to work with 0 or more whitespace between the numbers and alphabets.

Author

Commented:
I found the answer instead now.


char * str[100];
char alphabetBuf[100];
char alphabet[100];
int num1 = 0, num2 = 0;

str = "1+2";

sscanf(str, "%d%[^0-9]%d", &num1, alphabetBuf, &num2);
sscanf(alphabetBuf, "%s", alphabet); //to remove whitespace

This works if the string is
"1+2"
"1    +    2"


Cheers!
Yam
CERTIFIED EXPERT
Author of the Year 2009

Commented:
Hi YamSeng,
You've requested to delete this question, but its status remains as 'Pending Delete' because one or more comments have been added.  Normally, the only way to fully delete such a Question is to post a message to Community Support and ask for assistance.

EE is making a one-time database sweep to purge the Pending Delete Questions automatically.  During this sweep:

    YamSeng -- To allow the deletion to proceed:  Do nothing.
    EXPERTS -- Please DON'T POST a comment except to contest this deletion.

In the future, please refer to http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp#8 for instruction on deleting questions.

DanRollins -- EE database cleanup volunteer
30 points refunded, item closed and moved to our PAQ rather than deleted since this information may help others.
Moondancer - EE Moderator

Explore More ContentExplore courses, solutions, and other research materials related to this topic.