austinscode
austinscode

Reputation: 255

Error checking for strInput to notify user of an input too large for the program?

I'm simply trying to implement some error checking in my program.

The program converts strings that are 100 characters or less to words that look like the following hello->hElLo. So every other letter is capitalized. So I simply want to add a statement that tells the user the input is too large and asks them to re-enter a word. Here is what I have, but it just outputs To large. no matter what is entered, then quits the program.

int main(){
/*Read word from the keyboard using scanf*/
char strInput[100];
printf("Input word that is 100 characters or less: \n");

scanf("%s", strInput);
/*Call studly*/
studly(strInput);
/*Print the new word*/
if (strInput > 100){
    printf("To large.");
}
else{
printf("%s", strInput);
}


return 0;
}

This is just the main function but I think the only thing I need to do is change my if and else statements. Just not sure how to check size of char strInput[100] in the if statment. Also let me know if there is a simple way to handle spaces. Thanks for your help!

Upvotes: 1

Views: 161

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You can use fgets and strchr to check if the string contains a trailing newline:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char strInput[100], *ptr;

    printf("Input word that is 100 characters or less: \n");
    fgets(strInput, sizeof strInput, stdin);
    if ((ptr = strchr(strInput, '\n')) == NULL) {
        printf("Too large.\n");
    } else {
        *ptr = '\0';
        printf("%s\n", strInput);
    }
    return 0;
}

Upvotes: 2

Related Questions