Here's part of the description of the assignment: The program must stop
accepting input when the user enters the word done. Assume that no word is
more than 20 letters long.
I have to validate that if a word is more than 20 characters thy will get an error message and have to retype again. Also when I type done, the program should end. Im not sure how to write these statements correctly. When I run it and type more then 20 characters it gives me an error - Expression: L("Buffer is too small" &&0)
Here's my Code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXCHAR 20
int charcount(char []);
int main()
{
char message[MAXCHAR];
int numofchar;
printf("Enter any word to display how many characters that word has.\nA word CANNOT be more than 20 charatcers long.\n");
printf("When you are finished type the word done.\n");
do
{
printf("\nEnter a word: " );
gets_s(message, MAXCHAR);
numofchar = charcount(message);
while ( numofchar > MAXCHAR)
{
printf("The word enterd is more then 20 characters. Try again.\n");
printf("Enter a word: " );
gets_s(message, MAXCHAR);
}
printf("The word %s has %d characters.\n", (message),numofchar);
} while ( (message,MAXCHAR) != 'done');
printf("\nEnd of program.\n");
system ("PAUSE");
return 0;
}
int charcount (char list[])
{
int i, count = 0;
for(i = 0; list[i] != '\0'; i++)
count++;
return(count);
}
To detect an error, you simply need to check the return value of get_s:
http://msdn.microsoft.com/en-us/library/5b5x9wc7%28v=vs.90%29.aspx
int main()
{
char message[MAXCHAR], *s;
int numofchar;
...
do
{
printf("\nEnter a word: " );
s = gets_s(message, MAXCHAR);
if (!s) {
<< some error handling code goes here >>
...
Related
I want my user to enter the input which I have set only for each and every declaration, but when I tried running the program it still proceeds, for example, name the ic_size the limit character is only 12 character input, but if I put more than 12 it just accepts it as nothing wrong. Here's the coding I tried:
void login_register()
{
const name_size = 80;
char name[name_size];
const ic_size = 12;
char ic[ic_size];
const no_size = 12;
char no[no_size];
const nationality_size = 20;
char nationality[nationality_size];
const email_size = 50;
char email[email_size];
int select;
int Day =0;
int bed_tax =0;
double RM;
double room_price=0;
double service_tax = 0;
double total = 0;
char term,check;
printf("\n Please enter your name : ");
while(gets(name))/* same as scanf ("%s",name) %s mean print the corresponding argument in string*/
{
if(!isalpha && sizeof(name) > name_size) // restrict user input can only be alphabeth and must not exceed array size
{
printf("\n Please enter a valid input");
}
else
{
break;
}
}
printf(" Please enter your IC number : ");
while(gets(ic))
{
if(isdigit && sizeof(ic) < ic_size) // restrict user input can only be numerical and must not excedd array size
{
printf("\n Please enter a valid input");
}
else
{
break;
}
}
printf(" Please enter your phone number : ");
while(gets(no))
{
if(isdigit && sizeof(no) < no_size)
{
printf("\n Please enter a valid input");
}
else
{
break;
}
}
printf(" Please enter your nationality : ");
while(gets(nationality))/* same as scanf ("%s",nationality) %s mean print the corresponding argument in string*/
{
if(!isalpha && sizeof(nationality) > nationality_size) // restrict user input can only be alphabeth and must not exceed array size
{
printf("\n Please enter a valid input");
}
else
{
break;
}
}
printf(" Please enter your email : ");
while(gets(email))/* same as scanf ("%s",email) %s mean print the corresponding argument in string*/
{
if(!isalpha && sizeof(email) > email_size) // restrict user input can only be alphabeth and must not exceed array size
{
printf("\n Please enter a valid input");
}
else
{
break;
}
}
Rather than gets(), which has no limit on user input, consider fgets().
Shift design goal to:
Allow unlimited input per line, but only save up to N characters of input.
Let user know if too much entered. Try again if needed.
I recommend a helper function that prompts, reads input, and handles long lines.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
// 'size' is the size of the array 'destination' points to.
int get_user_input(const char *prompt, size_t size, char *destination) {
char buf[size + 2]; // size + \n + 1 extra
do {
fputs(prompt, stdout);
if (fgets(buf, sizeof buf, stdin) == NULL) {
*destination = '\0';
return 0; // End of file
}
char *end_of_line = strchr(buf, '\n');
if (end_of_line) {
*end_of_line = '\0'; // Lop off \n
} else {
// get rest of line
scanf("%*[^\n]"); // Read everything up to a \n and toss
scanf("%*1[\n]"); // Read a \n and toss
}
} while (strlen(buf) >= size);
strcpy(destination, buf);
return 1;
}
Now read as needed. Recall that name_size = 12 means up to 11 characters are saved as 1 more is needed to save the null character. Adjust name_size as needed.
int main(void) {
const int name_size = 12;
char name[name_size];
const int nationality_size = 20;
char nationality[nationality_size];
get_user_input("Please enter your name: ", sizeof name, name);
printf("Name <%s>\n", name);
get_user_input("Please enter your nationality: ", sizeof nationality, nationality);
printf("Nationality <%s>\n", nationality);
}
This might be a rookie question, but I need to make sure that the input given by the user is of data type char [%c] or a string [%s].
If it were an integer, I would just do something like this:
int data, x;
do {
printf("Please enter a number: ");
x = scanf(" %d", &data);
getchar();
} while(x!=1);
So I was wondering if there's a similar way to do this, if the input is supposed to be a string or a character. Thanks, Any help would be appreciated!
Avoid to use %c in scanf() because some unexpected character like \r\n will be input.
You can use a char[2] to receive a single character. An \0 will be filled after your string to represent the end of string, so the length of array must be bigger than 1.
An example:
#include <stdio.h>
int main()
{
char data[2];
scanf("%1s", data);
if (data[0] >= 'a' && data[0] <= 'z') // custom your constraint here
{
// legal
printf("legal: %s", data);
}
else
{
// illegal
printf("illegal: %s", data);
}
return 0;
}
While I input b, the data will be "b\0".
part of the answer is if you just want to read only alphabet you can use below.
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
do {
printf("enter a char:");
scanf(" %c",&ch);
}while(!isalpha(ch));
printf("%c",ch);
return 0;
}
Update 1:
Just for the completeness and for the FUN part of the programing, have added code here.
This works well (not tested robustly, you can do if you need to) for the single char input or for a string of length 9.
Remember to type the EOF after input is entered in case length of input is < 9.
and read EOF behavior on same line and new line.
#include <stdio.h>
#include <ctype.h>
#define LEN 10
int main()
{
char ch;
char str[LEN] = {0};
int i = 0;
int ret;
printf("enter a char or string(len = 9) and press EOF if len < 9\n");
do {
if(1== (ret = scanf(" %c",&ch)))
{
if(isalpha(ch))
str[i++] = ch;
}
else
printf("scanf:Error (%d)\n", ret);
}while(ret != EOF && ( !isalpha(ch) || i < LEN-1));
str[i] = '\0';
printf("str is %s\n",str);
return 0;
}
I'm working in a problem from the "C programming a Modern Approach 2nd Edition" text. I want to write a program that writes the smallest and largest words. The program stops accepting inputs when the user enters a 4-letter word.
I'm using an array of strings to solve this but I can't even get my program to store words in it.
#include <stdio.h>
#include <string.h>
#define WORD_LEN 20
int main()
{
char word[WORD_LEN]={0},ch;
char *a[10]={}; //Max 10 words in the array
int i=0,j;
for(;;)
{
printf("Enter a word: ");
fgets(word,WORD_LEN,stdin);
strtok(word, "\n"); //removes newline
a[i] = word;
if(strlen(word) == 4) //if word is 4 characters
break; //break out of loop
i++;
}
for(j=0;j<i;j++) //displaying array
printf("%s\n",a[j]);
return 0;
}
Output:
Enter a word: Analysis
Enter a word: Martin
Enter a word: Jonathan
Enter a word: Dana
Dana
Dana
Dana
Any idea into what I'm doing wrong? Thanks.
As BLUEPIXY mentioned, you are storing same address in all a[i]s. So at the end of the loop, it prints the last output i times.
Solution:
You need to allocate memory for a[i] and copy the strings.
#include <stdio.h>
#include <string.h>
#define WORD_LEN 20
#define MAX_NUM_WORD 10 //Max 10 words in the array
int main()
{
char word[WORD_LEN]={0},ch;
char *a[MAX_NUM_WORD]={0};
int i=0,j;
for(;;)
{
printf("Enter a word: ");
fgets(word,WORD_LEN,stdin);
strtok(word, "\n"); //removes newline
a[i] = malloc(sizeof(char)* (strlen(word)+1)); //1 for '\0'
strcpy(a[i], word);
i++;
if(strlen(word) == 4) //if word is 4 characters
break; //break out of loop
//i++; //You will be missing last 4 letter word if i++ is here.
if(MAX_NUM_WORD <= i) //You can store only MAX_NUM_WORD strings
break;
}
for(j=0;j<i;j++) //displaying array
printf("%s\n",a[j]);
//Your other code.
for(i=0; i<MAX_NUM_WORD && NULL != a[i]; i++)
free(a[i]); //Free the allocated memory.
return 0;
}
Adding to others answers, when using malloc to allocate memory for your strings, it is good to also check the return value of void* pointer returned from it.
Additionally, it is also safe to check the return value of fgets, just to be super safe.
This solution demonstrates these points:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WORD_LEN 20
#define MAX_NUM_WORD 10
#define EXIT_LEN 4
int
main(void) {
char word[WORD_LEN];
char *a[MAX_NUM_WORD];
int i = 0, wrd;
while (i < MAX_NUM_WORD) {
printf("Enter a word: ");
if (fgets(word, WORD_LEN, stdin) != NULL) {
word[strlen(word)-1] = '\0';
}
a[i] = malloc(strlen(word)+1);
if (a[i] == NULL) {
fprintf(stderr, "%s\n", "Malloc Problem");
exit(EXIT_FAILURE);
}
strcpy(a[i], word);
i++;
if (strlen(word) == EXIT_LEN) {
break;
}
}
// Print and free, all at once.
for (wrd = 0; wrd < i; wrd++) {
printf("%s\n", a[wrd]);
free(a[wrd]);
a[wrd] = NULL;
}
return 0;
}
I am trying to enter an array of numbers (only integers for now) and what I wan't to do is if the user enters all the needed numbers, give him the ability to break the operation of entering numbers and skip to printing the entered numbers. My code is below. So the thing is, I've set 100 array elements, but if only have 5 to enter I don't wan't to enter the other 95.
Commented code is what I've tried and it didn't work. ( I work in CodeBlocks and am a total beginner, so I'm still learning this...)
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declaring variables
int one_d_array[100],counter=0;
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
for (counter=0;counter<5;counter++){
scanf("%d",&one_d_array[counter]);
/*if (one_d_array[counter]==00){
break;
}*/
}
printf("Entered list is:\n");
for (counter=0;counter<5;counter++){
printf("%d\n",one_d_array[counter]);
}
}
return 0;
}
fgets can be used to input a line. If the line is 00 exit the loop. Otherwise sscanf tries to scan a number.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( void)
{
int one_d_array[100],each=0,counter=0;
char input[99] = "";
printf("Enter a list of numbers(max. 100)\nTo end, enter two zeros (00)\n");
while ( 1){
if ( fgets ( input, sizeof ( input), stdin)) {//get a line
if ( strcmp ( input, "00\n") == 0) {//exit on 00
break;
}
if ( ( sscanf(input, "%d",&one_d_array[counter])) != 1) {// != 1 means sscanf failed
printf("could not scan a number try again\n");
continue;
}
counter++;
printf("numbers input: %d\n\n", counter);
if ( counter >= 100) {
break;
}
}
else {
fprintf ( stderr, "problem reading input\n");
exit ( 1);
}
}
printf("Entered list is:\n");
for (each=0;each<counter;each++){
printf("%d\n",one_d_array[each]);
}
return 0;
}
Variable names cannot start with a number, so I've edited it accordingly.
#include <stdio.h>
#include <stdlib.h>
int main(){
//Declaring variables
int oneD_array[100],counter=0, num=0;
char c[3];
do{
printf("Enter your %d number, q to quit", counter+1);
scanf("%s",&c);
if(c == "q" || c == "Q"){
break;
}
else{
num = atoi(c);
oneD_array[num];
counter++;
}
}while(c != "q");
printf("Entered list is:\n");
for (int i = 0;i<counter;i++){
printf("%d\n",oneD_array[i]);
}
}
return 0;
}
I have the task to count the number of letters in random words until "End" is entered. I'm not allowed to use the strlen(); function. That's my solution so far:
#include <stdio.h>
#include <string.h>
int stringLength(char string[]){
unsigned int length = sizeof(*string) / sizeof(char);
return length;
}
int main(){
char input[40];
while (strcmp(input, "End") != 0) {
printf("Please enter characters.\n");
scanf("%s", &input[0]);
while (getchar() != '\n');
printf("You've entered the following %s. Your input has a length of %d characters.\n", input, stringLength(input));
}
}
The stringLength value isn't correct. What am I doing wrong?
The %n specifier could also be used to capture the number of characters.
Using %39s will prevent writing too many characters into the array input[40].
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( void)
{
char input[40] = {'\0'};
int count = 0;
do {
printf("Please enter characters or End to quit.\n");
scanf("%39s%n", input, &count);
while (getchar() != '\n');
printf("You've entered the following %s. Your input has a length of %d characters.\n", input, count);
} while (strcmp(input, "End") != 0);
return 0;
}
EDIT to correct flaw pointed out by #chux.
using " %n to record leading space and %n" record total characters this should record the number of leading whitespace and the total characters parsed.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
char input[40] = {'\0'};
int count = 0;
int leading = 0;
do {
printf("Please enter characters. Enter End to quit.\n");
if ( ( scanf(" %n%39s%n", &leading, input, &count)) != 1) {
break;
}
while (getchar() != '\n');
printf("You've entered %s, with a length of %d characters.\n", input, count - leading);
} while (strcmp(input, "End") != 0);
return 0;
}
EDIT stringLength() function to return length
int stringLength(char string[]){
unsigned int length = 0;
while ( string[length]) {// true until string[length] is '\0'
length++;
}
return length;
}
Please note that sizeof is evaluated at compile time. So it can't be used to determine the length of a string in run time.
The length of a string is the number of characters until you encounter a null-character. The size of a string is thus one more than the number of characters. This final null-character is called the terminating null character.
So to know the length of a string in run-time, you have to count the number of characters until you encounter a null-character.
Programming this in C is simple; I leave this to you.