测试有关scanf返回值的所有情况

时间:2015-11-17 10:07:52

标签: c scanf

使用下面的代码,如果我输入1个字符串和ctrl-D,它将打印出没有用两个字扫描​​并退出。但是,如果我输入3个或更多字符串,则需要前两个字符串并将其余部分丢弃。如何解释这一点 - 如果输入两个以上的字符串,则退出?

int scan_count = 0;

printf("Enter two strings: \n");

scan_count = (scanf("%s %s", first_word, second_word));
if (scan_count != 2)
{
    printf("Did not scan in two words successfully, exiting.\n");
    exit(2);
}

2 个答案:

答案 0 :(得分:2)

一个常见的用法是尝试更多地读取一个字符串:

char dummy[2];
scan_count = (scanf("%s %s %1s", first_word, second_word, dummy));

但是这只有在用Ctrl-D终止输入时才有效。如果您想知道是否恰好包含2个字,则必须先使用fgets获取该行,然后将其与sscanf分开:

char line[SIZE], dummy[2];
printf("Enter two strings: \n");
cr = fgets(line, sizeof(line), stdin); /* should test cr againt NULL - omitted for brievety */
if (strchr(line, '\n') == NULL) {
    ...  /* no EOL : line too long*/
}
scan_count = (sscanf("%s %s %1s", first_word, second_word, dummy));
if (scan_count != 2) ...

答案 1 :(得分:0)

我知道这很难看,但它确实起作用了:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int checkString(char *s1, char *s2){
    int c=0,i = 0,j=0,count1 = 0,count2 = 0,res = 0;

    while ((c = getchar()) != '\n' && c != EOF){
        s1[i++] = (char) c;
        if(c ==' '){
            count1++;
        }
    }
    s1[i]='\0';

    while ((c = getchar()) != '\n' && c != EOF){
        s2[j++] = (char) c;
        if(c ==' '){
            count2++;
        }
    }
    s2[j]='\0';

    if((strlen(s1) == 0) || (strlen(s2) == 0)){
        return res = 0;
    }else if((count1 + count2) == 0){
        res = 2;
    }

    return  res;
}

int main(void){
    char first_word[50];
    char second_word[50];
    int scan_count = 0;

    printf("Enter any string : ");
    if ((scan_count = checkString(first_word,second_word)) != 2){
        printf("Did not scan in two words successfully, exiting.\n");
        exit(2);
    }else{
        printf("You typed two strings.\n");
    }
    return 0;
}

输出1:

Enter any string : michael jackson
michael
Did not scan in two words successfully, exiting.

输出2:

Enter any string : Michael
Jackson
You typed two strings.