Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

beginner, getchar( )

nightsurfernightsurfer Member Posts: 272
Hi,

I'm just starting with C in one of m courses, and we were asked to write a program that reads in a date from the user and outputs it in canonical form (dd/mm/yyyy). There were various requirements about what forms the data could take, adn the output for various invalid entries.

In any case, I can't test whether or not my logic works correctly since my program is hanging on the first getchar() call. My code is shown below. The program hangs at the first while() loop.

Thanks for your help.

[code]
#include

main() {
int c = 0;
int year = 0;
int month = 0;
int day = 0;
int errorCode = -1;
int x = 0;

printf("starting
");

while ((c = getchar()) - '0' < 0 || c - '0' > 9){printf("blah");};
x = c - '0';
while ((c = getchar()) - '0' > -1 && c - '0' < 10) {
printf("got to here");
x = x * 10 + (c - '0');
}
if (x < 0) {
errorCode = 0;
}
else if (x > 30) {
errorCode = 1;
}
else if (x > 12 && errorCode < 0) {
day = x;
x = 0;
month = -1;
}
else if (x < 13 && errorCode < 0) {
month = x;
x = 0;
day = -1;
}
while ((c = getchar()) - '0' > -1 && c - '0' < 10) {
x = x * 10 + (c - '0');
}
if (x < 0) {
errorCode = 0;
}
else if (x > 30) {
errorCode = 1;
}
else if (x > 12 && errorCode < 0 && day == -1) {
day = x;
x = 0;
}
else if (x > 12 && errorCode < 0 && month == -1) {
errorCode = 2;
x = 0;
}
else if (x < 13 && errorCode < 0 && month == -1) {
month = x;
x = 0;
}
else if (x < 13 && errorCode < 0 && day == -1) {
errorCode = 2;
x = 0;
}
while((c = getchar()) - '0' > -1 && c - '0' < 10 && x < 1000) {
x = x * 10 + (c - '0');
}
if (x < 0) {
errorCode = 0;
}
else {
year = x;
}
while ((c = getchar()) != '
'){};
if (errorCode == 0) {
printf("overflow");
}
else if (errorCode == 1) {
printf("invalid");
}
else if (errorCode == 2) {
printf("ambiguous");
}
else {
printf("%d", day);
printf("/");
printf("%d", month);
printf("/");
printf("%d", year);
printf("
");
}
printf("exiting");
}
[/code]


There are two methods in software design. One is to make the program so simple, there are obviously no errors. The other is to make it so complicated, there are no obvious errors.

Comments

  • Justin BibJustin Bib USAMember Posts: 0

    _________ / http://forcoder.org / free ebooks and video tutorials about ( Visual Basic .NET, MATLAB, Assembly, Visual Basic, Delphi, C#, C++, Java, Scratch, Ruby, PL/SQL, Python, R, PHP, Objective-C, Swift, JavaScript, Go, C, Perl SAS, Hack, Lua, Rust, Crystal, Apex, LabVIEW, Erlang, Dart, Prolog, Logo, Lisp, FoxPro, Julia, Alice, Scheme, Fortran, Awk, Bash, Kotlin, D, Clojure, Transact-SQL, VBScript, Scala, ABAP, ML, COBOL, Ada, F# ) _________

Sign In or Register to comment.