Monday, December 28, 2009

Friday, December 18, 2009

C input routine for single character and string

By answering some beginner questions in the programming forum, I am trying to learn some C/C++ again. As a matter of course, I learned something new as always, this is a page I referred to when trying to clear the buffer in stdin.

The first example is for capturing single character and check if it is a number between 1 and 4:

char option;
int number;
do {
puts("Please enter your choice:");
fflush(stdout);
if (fgets(&option, 2, stdin) != NULL) {
if (option != '\n') {
scanf("%*[^\n]"); // get rid of the non-newline characters
scanf("%*c"); // get rid of the newline character
}
}
} while (!(sscanf(&option, "%d", &number) == 1 &&
number >= 1 && number <= 4));


The 2nd example is for capturing a string with trimming, overflow protection and emptyness checking:


char fileStr[20];
char *pointer = fileStr;
bool tooLong = false;

do {
printf("\nPlease input a file name: ");
fflush(stdout);
if (fgets(fileStr, sizeof fileStr, stdin) != NULL) {
tooLong = false;
if (*fileStr != '\n') {
// search for newline character
char *newline = strchr(fileStr, '\n');
if (newline != NULL) {
*newline = '\0'; /* overwrite trailing newline */
pointer = trimwhitespace(pointer); /* trim the line */
} else {
/* clear the stdin since user input too much */
tooLong = true;
scanf("%*[^\n]");
scanf("%*c");
}
}
}
} while (tooLong || *pointer == '\0' || *pointer == '\n');

printf("file name = \"%s\"\n", pointer);


Pay special attention on the variable you are gonna use at last, it is "pointer".

Tuesday, December 08, 2009

Birt and java.lang.NoClassDefFoundError: org/w3c/tidy/Tidy Tidy.jar

Lately I have been debugging a customer issue with our birt integration. The exception message is java.lang.NoClassDefFoundError: org/w3c/tidy/Tidy. We have found a lot of posts in google with this error.

Most of the google results and this one are related to the file/folder permission, and the location of the jars in tomcat/websphere. Our integration is not involved with any webapp container, and we double check few times the file/folder permission is okay.

And then, I know that lsof can show what jars the java process has linked. That shows all the jars are marked as "deleted". That is a big hint to me. Something is wrong with the java process and this time, we found that, the same java process had been launched twice. This is a good lsof tutorial btw.

Friday, December 04, 2009

Javascript window.event.keyCode in firefox

This is usually used for capturing the ENTER key pressed in the html text box:
function onkeypressed(e) {
var keyCode = (window.event) ? window.event.keyCode : e.which;
if (keyCode == 13) {
// do something
return true;
} else {
return false;
}
}