Fenraehl Fenraehl - 1 month ago 6
C Question

while() loop lets program crash, but there are no syntax errors or anything else

I need to write a program, which let's the user type in a string and then proceeds to check the single char with

islower
,
isupper
,
isdigit
, but at the first loop for the string it always crashes and gives to
printfs
at a time after second turn.

Can somebody help please?

#include <stdio.h>
#include <string.h>
#ifndef MAIN_H_
#include "main.h"
#endif

int main()
{
char cString[MAX]; //alle Felder auf NULL gesetzt für spätere Überprüfung ob Entertaste gedrückt wurde
char cUebergabe[MAX];
int iLauf=0;
int iNULL=0;

while(iLauf<MAX)
{
cString[iLauf]=iNULL;
iLauf++;
}
iLauf=0;

printf("geben sie maximal 20 Zahlen zur auswertung des String ein, bei der Eingabe von Enter ohne ein Symbol wird das Einlesen abgebrochen\n");

while(iLauf<MAX)
{
printf("Geben Sie nun das %d . Zeichen ein\n",iLauf+1);

scanf("%c",&cString[iLauf]);
iLauf++;

if(cString[iLauf-1]==iNULL)
{
iLauf=MAX;
}
else
;
}
strcpy(cUebergabe,cString);

VerarbeitungAusgabe(cUebergabe, iNULL);

return 0;
}

Answer

The problem is that %c format specifier suppresses skipping of leading white space characters. And the new line (when the user presses Enter) is read in the next iteration after the number is read.

From the man page:

Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the for‐ mat.

So just prepend a space:

scanf(" %c", &cString[iLauf]);

Also note, you can easily fill memory with zeroes with memset. So you can replace this:

while (iLauf < MAX) {
  cString[iLauf] = iNULL;
  iLauf++;
}
iLauf = 0;

with this:

memset(cString, 0, sizeof(cString));

or even this:

char cString[MAX] = {0};
Comments