0

I want to read an unknown number of characters, which are not greater than 10.

char word[10];
for( i=0;i<10;i++){
    if( !scanf("%c",&word[i])){ //terminate with 0
        getchar();
        break;
    }   
} 

The problem is that number is also an character, so the if statement won't be executed. Is there any other solution to terminate the input of characters for example with 0.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Boris
  • 17
  • 4
  • 2
    hint: `scanf()` does not return the scanned entry, it returns the number of items scanned and matched scussfully. – Sourav Ghosh Jun 24 '20 at 10:42
  • So if I type in 0, then nothing is scanned? – Boris Jun 24 '20 at 10:45
  • Why not? but it does not return a 0, in case the scanning is successful. – Sourav Ghosh Jun 24 '20 at 10:46
  • So in that case I have to write: scanf(..)==0. – Boris Jun 24 '20 at 10:50
  • I suggest to use getchar() for reading single chars. This post is related https://stackoverflow.com/questions/14419954/reading-a-single-character-in-c – Jonny Schubert Jun 24 '20 at 10:52
  • "*The problem is that number is also an character, so the if statement won't be executed.*" - Could you elaborate that? The `if` statement will *always* get executed. Not clear what you mean with "number is also an character" as well. Please add more details, actual input and output and expected output. – RobertS supports Monica Cellio Jun 24 '20 at 10:59

3 Answers3

0

You can use a do..while loop. Something like (pseudo-code)

int keep_looping = 1;
int counter = 0;
do {
    ret = scanf(" %c",&word[counter]);
    if (!ret) continue;  //can use more cleanup and error check
    if (word[counter] == '0') keep_looping =0;
    counter++;
    }
while (keep_looping && counter < 10)
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

you can check the character that you just read (at word[i]) and if not valid (e.g not alpabetical) than break.

LiozN
  • 1
0

Suggest:

char word[10];

if( scanf("%9s",word) != 1 )
{
    fprintf( stderr, "scanf for (max 9 char word) failed\n" );
    exit( EXIT_FAILURE );
}   

using %9s because the %s input format conversion specifier always appends a NUL byte to the input.

If the input is less than 9 characters, that is properly handled.

If the input is greater than 9 characters, the 9 modifier will stop the input, so the input buffer is not overflowed. Such an overflow would result in undefined behavior.

user3629249
  • 16,402
  • 1
  • 16
  • 17
  • So in order to input 10 characters, I have to change %9 to %10 and char word[11], so that in position word[10] is the NUL byte? – Boris Jun 28 '20 at 09:49