PDA

View Full Version : C program: reading chars then ints


Math Is Hard
Jul18-04, 09:03 PM
The assignment states: "Write a code fragment that reads and discards all characters from standard input until it encounters a "=", and then reads the following characters as an int."

I have a couple of problems:
1) reading char values as int, for instance if I input abc=123 there's no problem, but if I input abc=abc, then there's trouble. I was thinking the ASCII value would be read and stored, but it's not happening.

2) the instruction "reads the following characters as an int". If I input ABC=ABC, should the program only end up printing the value of C as the integer?

Here's what I have so far - I am including the whole program. Thanks for your advice.

#include <stdio.h>
int main(void)
{
char mychar;
int myint;

while((mychar = getchar())!= '=')
{
continue;
}

scanf("%d", &myint);
printf("%d", myint);

return 0;
}

chroot
Jul18-04, 09:09 PM
It seems your program meets the specification. The specification does not instruct you to do any kind of type-checking on the characters themselves to see if they are decimal numerals.

Although it seems your program meets the spec, the spec is admittedly incomplete (it would be unacceptable in industry!). If I were you, I'd call the professor and make sure (s)he didn't intend to provide any more specifics.

- Warren

Math Is Hard
Jul18-04, 10:50 PM
Thanks, Warren. I will email my prof about this and see if I can get more clarification.

Math Is Hard
Jul20-04, 01:14 PM
My teacher said if I wanted a challenge I should code the assignment to accept either an integer or a character after the '=' sign. I thought maybe I could write this so that if characters are entered I could display the ASCII value of the first one entered. But now I am getting stuck since I used scanf() to read an integer I don't know how to handle a character being entered.
thanks.

#include <stdio.h>
int main(void)
{
char mychar;
int myint;

while((mychar = getchar())!= '=') //discard all until = is read
{
continue;
}
if (scanf("%d", &myint) == 1)
{
printf("That was an integer\n");
printf("It's value is %d\n", myint);
}
else
{
printf("That was NOT an integer\n");
printf("The ASCII value of the first character is...\n");
}
// now I am stuck
return 0;
}

chroot
Jul20-04, 01:20 PM
The easiest way is to use ungetc() to push the character back onto the stream. That way you can "peek" at it, make a decision about it, then call scanf on the stream.

Alternatively, you can read your chars into an array and then use sscanf on the array.

- Warren

Math Is Hard
Jul20-04, 01:24 PM
ungetc() huh? That's a new function for me. Cool- I am intrigued - I am going to play with that. Thanks!
I hadn't thought about using an array, either. We are just starting to work with those. hmmm....

Hurkyl
Jul20-04, 03:31 PM
Hrm, the istream classes have a "peek" function; stdio.h doesn't have an equivalent? :frown: