简体   繁体   中英

How to scanf a string until specific word occurs

Input: I want to be something END. END is is that specific word. I need to store all my words.

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

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

Is this the right way ?

If I have understood your question correctly then you need something like the following.

#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 );
    }        
}

The program output is

one
two
three
four

Or something like the following

#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 );
    }        
}

If to enter

one two three four end

then the output will be

one
two
three
four
#include<stdio.h>
#include<string.h>
/*Description: How to scanf a string until a specific word occurs*/

int main(){
    char row[6][10];
    int p=0;
    //I want to be something END. ( 6 words for input.)
    printf("Please enter a word.\n");
    /*
    do
    {
        scanf("%s", row[p]);
        p++;

    }while(strcmp(row[p],"END")!=0);
    //Above loop runs forever(or until row runs out of space), because p increments after info is read
    */
    do
    {
        scanf("%s", row[p]);
        p++;

    }while(strcmp(row[p-1],"END")!=0);
    //This loop ends once string just read in from keyboard/user equals "END"

    return 0;
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM