首页 > 解决方案 > 如何扫描字符串直到出现特定单词

问题描述

输入:我想成为某种东西 END。END 是那个特定的词。我需要存储我所有的话。

do
    {
        scanf("%s", row[p]);
        p++;

    }while(strcmp(niz,'END')!=0);

这是正确的方法吗?

标签: carraysstring

解决方案


如果我正确理解了您的问题,那么您需要以下内容。

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

char * string_toupper( char *s )
{
    for ( char *p = s; *p; ++p ) *p = toupper( ( unsigned char )*p );

    return s;
}

int main( void )
{
    enum { N = 50 };
    char word[N];
    char tmp[N];

    const char *s = "one two three four end five";

    for ( int offset = 0, pos = 0; 
          sscanf( s + offset, "%s%n", word, &pos ) == 1 && strcmp( string_toupper( strcpy( tmp, word ) ), "END" ) != 0;
          offset += pos )
    {
        puts( word );
    }        
}

程序输出为

one
two
three
four

或类似以下内容

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

char * string_toupper( char *s )
{
    for ( char *p = s; *p; ++p ) *p = toupper( ( unsigned char )*p );

    return s;
}

int main( void )
{
    enum { N = 50 };
    char word[N];

    for ( char tmp[N]; scanf( "%s", word ) == 1 && strcmp( string_toupper( strcpy( tmp, word ) ), "END" ) != 0; )  
    {
        puts( word );
    }        
}

如果要进入

one two three four end

那么输出将是

one
two
three
four

推荐阅读