Hello, I am still green to the C programming language. I am writing a multi-dimensional array program to store strings into an array. The program requires error checking to avoid overflow.

I am using Visual Studio 2008.
I am using a Windows O/S.

The program runs fine on the first past through, but skips over the prompt on the next run.

Here is the output:

Please enter a word: word
Are you finished: Please enter a word:

Here is my code:

#include "stdafx.h"
#include <string.h>
#define MAX 25
#define LENGTH 16

int _tmain(int argc, _TCHAR* argv[])
{
	char store[MAX][LENGTH];
	char word[LENGTH];
	int i=0;
	char exit='n';
	
	while(exit!='y'||i==MAX)
	{
		printf("Please enter a word: ");
		scanf("%s",&word);
		printf("\n");
		while(strlen(word)>15)
		{	
			memset(word, NULL, LENGTH);
			printf("You have entered a word that is to large.\n");
			printf("Please enter a word: ");
			scanf("%s",&word);
		}
		strcpy(store[i], word);
		printf("Are you finished: ");
		scanf("%c",&exit);
		i++;
	}
	return 0;
}

Thank you for your help.

Your error check is not going to work. Why? Because if someone enters more than 16 characters then the entire program will get trashed and there is nothing that you can do to avoid it. That's one of the problems with scanf().

What I would do is get the string one character at a time and produce an error on the first character that would overflow the destination character array.

How would I go about doing that?

Use scanf("%c",&word); instead?

Thanks again!

The error checking seems to work, I can enter a random string that is longer than 15 characters. It goes into the while and prompts me to enter one smaller than 15. It keeps me in the loop until I one the correct size.

Thanks again!

seems to work is misleading. scanf() will scribble all over memory when you type more than 15 characters. The solution is to either use getchar() or scanf("%15s"); But with scanf() you will not know whether there are more keys or not in the keyboard buffer.

int c;
int i = 0;
while( (c = getchar()) != '\n')
{
    word[i++] = c;
}

Thank you for your help, I am sorry for being such a nuisance.

P.S.
Sorry for not using "Code Tags."
I am also sorry for the title "Need help please."
I have just recently read over the rules.
I blame my procrastination for it.


Thank you for my first post.

Thank you for your help, Dragon.
Thank you for your help, WaltP.

>>I have just recently read over the rules.
It's about time. But better late than never :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.