Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to read a c-string and then an int with a single scanf in C?

Tags:

c

scanf

Hey, I'm trying to get this function to get the following output with the listed input, the "..." is where I'm not sure what to write:

void Question8(void)
{
  char sentence[100];    
  int grade;    
  scanf(….);    
  printf("%s %d", sentence, grade);    
}

Input:
My CS Grade is 1000

Output:
My CS Grade is 100

However, the kicker is that I need the scanf to read a c-string and then an int with a single scanf command, is this even possible?

Edit: I can only edit the code in the location with the three periods ( "..." ), I cannot use anything more. I can assume that the input listed is expected but I cannot change anything outside of the three periods. The output does not contain typos, the purpose of this assignment is to use flags and escape sequences.

like image 858
James Linden Avatar asked Jan 31 '11 07:01

James Linden


2 Answers

It is possible to read pre-formatted string using scanf, however the format must be strict. This version will continue to read the input until a digit is encountered and then read an integer. Here is your code again:

  char sentence[100];
  int grade;
  scanf("%[^0-9] %d",sentence,&grade);
  printf("%s %d\n", sentence, grade);
like image 80
Shamim Hafiz - MSFT Avatar answered Oct 12 '22 10:10

Shamim Hafiz - MSFT


I'll get this over with quick:

<obligatory_rant>
    stupid question, but I guess it's homework and you're
    stuck with these absurd limitations
</obligatory_rant>

Then, if you need to read everything up to but excluding the first digit, then the number:

if (scanf("%100[^0-9] %3d", text, &number) == 2)
    ...

Notes:

  • 100 in "%100[... should be whatever your actual buffer size is to protect against buffer overrun.
  • The %3d documents that at most 3 digits should partake the the numeric value, so 1000 is correctly read as 100.
  • [^...] means the string made up of characters not ("^") in the following set, which is then specified as 0-9 - the digits.
  • if (... == 2) tests whether both positional parameters were scanned / converted successfully.

If you can't add an if and error message, then simply:

scanf("%100[^0-9] %3d", text, &number)
like image 20
Tony Delroy Avatar answered Oct 12 '22 10:10

Tony Delroy