Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

don't care in scanf

Tags:

c++

c

scanf

Imagine the following:

you read in a string with scanf() but you only need a few of the datapoints in the string.

Is there an easy way to throw away the extraneous information, without losing the ability to check if the appropriate data is there so you can still reject malformed strings easily?

example:

const char* store = "Get: 15 beer 30 coke\n";
const char* dealer= "Get: 8 heroine 5 coke\n";
const char* scream= "Get: f* beer 10 coke\n";

I want to accept the first string, but forget about the beer because beer is yuckie. I want to reject the second and third strings because they are clearly not the appropriate lists for the 7/11;

So I was thinking about the following construction:

char* bId = new char[16];
char* cId = new char[16];
int cokes;
sscanf([string here], "Get: %d %s %d %s\n", [don't care], bId, &cokes, cId);

This way I would keep the format checking, but what would I put for [don't care] that doesn't make the compiler whine?

Of course I could just make a variable I don't use later on, but that is not the point of this question. Also checking the left and right side seperately is an obvious solution I am not looking for here.

So, is there a way to not care about but still check the type of a piece of string in scanf and friends?

like image 982
NomeN Avatar asked Sep 11 '09 10:09

NomeN


People also ask

How do I ignore scanf?

Explanation: The %*s in scanf is used to ignore some input as required. In this case, it ignores the input until the next space or newline. Similarly, if you write %*d it will ignore integers until the next space or newline.

Why should I not use scanf?

The scanf() and fscanf() functions have undefined behavior if the value of the result of this operation cannot be represented as an integer. In general, do not use scanf() to parse integers or floating-point numbers from input strings because the input could contain numbers not representable by the argument type.

Can we use %s in scanf?

In general scanf() function with format specification like %s and specification with the field width in the form of %ws can read-only strings till non-whitespace part. It means they cannot be used for reading a text containing more than one word, especially with Whitespaces.

What can I use instead of scanf in C?

To convert the input, there are a variety of functions that you can use: strtoll , to convert a string into an integer. strtof / d / ld , to convert a string into a floating-point number. sscanf , which is not as bad as simply using scanf , although it does have most of the downfalls mentioned below.


1 Answers

Use a * as assignment suppression character after %

Example:

  sscanf([string here], "Get: %*d %s %d %s\n", bId, &cokes, cId);
like image 163
Curd Avatar answered Oct 10 '22 19:10

Curd