繁体   English   中英

“ printf(”行读取:%s \\ n“,输入);”将不会打印出完整的输入字符串。 C程序设计

[英]“printf( ”Line read: %s\n“, input );” wont print out the full input string. C programming

程序应打印以下内容:

$ this is a test
Line read: this is a test
Token(s): 
 this
 is
 a
 test
4 token(s) read

但这切断了Line的内容:

$ this is a test
Line read: this
Token(s): 
 this
 is
 a
 test
4 token(s) read

它只需要输入的第一个单词...

码:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char const *argv[])
{
    char input[ 256 ];
    char *token;

    while ( 1 )
    {   
        printf("$ ");

        fgets( input, 256, stdin );
        int count = 0;      
        token = strtok( input, " \n" );
        if ( count == 0 && strcmp( input, "exit" ) == 0 )
        {
            exit( 0 );
        }

        printf( "Line read: %s\n", input );
        printf( "Token(s): \n" );

        while( token != NULL )
        {
            count++;
            printf( " %s\n", token );
            token = strtok( NULL, " \n" );
        }   

        printf( "%d token(s) read\n\n", count );
    }
    return 0;
}

strtok()修改输入字符串,在每个令牌的末尾放置一个空字节。 因此,当您这样做时:

token = strtok(input, " \n");

它在input的第一个单词之后放置一个空字节。 当您打印input ,该空字节将终止字符串。

将打印input的行移到第一次调用strtok() 或者复制input并使用strtok()

使用inputTEMP复制输入的值,我使程序可以工作。 谢谢@Barmar。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char const *argv[])
{
    char input[ 256 ];
    char inputTEMP [ 256 ];
    char *token;

    while ( 1 )
    {   
        printf("$ ");

        fgets( input, 256, stdin );
        strcpy(inputTEMP, input);
        int count = 0;

        token = strtok( input, " \n" );

        if ( count == 0 && strcmp( input, "exit" ) == 0 )
        {
            exit( 0 );
        }
        if ( strcmp ( input, "exit") != 0)
        {
            printf( "Line read: %s", inputTEMP );               
        }


        printf( "Token(s): \n" );

        while( token != NULL )
        {
            count++;
            printf( " %s\n", token );
            token = strtok( NULL, " \n" );
        }   

        printf( "%d token(s) read\n\n", count );
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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