在c中扫描任意数量的字符

scan arbitrary number of chars in c

我想读取不超过 10 个的未知字符数。

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

问题是number也是字符,所以if语句不会执行。是否有任何其他解决方案来终止字符输入,例如 0.

您可以使用 do..while 循环。像(伪代码)

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)

您可以检查您刚刚阅读的字符(在 word[i] 处),如果无效(例如不是按字母顺序排列)则中断。

建议:

char word[10];

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

使用 %9s 因为 %s 输入格式转换说明符总是将 NUL 字节附加到输入。

如果输入的字符少于 9 个,则处理得当。

如果输入大于9个字符,9修饰符会停止输入,所以输入缓冲区不会溢出。这样的溢出会导致未定义的行为。