Outputting a poem in C with each word being on a new line
Frage
I have an assignment in a C programming class to output a poem with each word on a new line, using only the functions getchar
and putchar
. I have the majority of the program written, but I can't figure out how to only have one new line for multiple spaces. For example, when there is more than one space there is a gap in the output, which I don't want. Does anyone know how to correct this?
int main(int argc, const char * argv[])
{
/* Variables declared */
int iochar;
/* While loop */
while ((iochar = getchar() ) != EOF) {
/* If statement to return on alphabetic characters, not puncuation */
if (((iochar >= 'A') && (iochar <= 'Z')) || ((iochar >= 'a') && (iochar <= 'z'))) {
putchar(iochar);
}
/* If statement to produce a new line when a space is detected */
if (iochar == ' ') {
putchar('\n');
}
}
return 0;
}
Lösung
You could store the previous character in another variable and only output a line break when the current character is a space AND the previous character was not a space.
By the way: what is supposed to happen with numbers in the input?
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow