每行打印一个单词

时间:2015-01-09 20:33:51

标签: c string line

我需要编写一个程序,每行输出一个单词。这是我到目前为止所得到的:

#include <stdio.h>
main(){
    int c;
    while ((c = getchar()) != EOF){
        if (c != ' ' || c!='\n' || c!='\t')
            printf("%c", c);
        else 
            printf("\n");
    }
}

逻辑非常简单。我检查输入是否不是换行符,制表符或空格,在这种情况下它会打印它,否则会打印换行符。

当我运行它时,我得到这样的结果:

input-->  This is
output--> This is

它打印整件事。这里出了什么问题?

5 个答案:

答案 0 :(得分:7)

if (c != ' ' || c!='\n' || c!='\t') 这永远不会是假的。

也许你的意思是: if (c != ' ' && c!='\n' && c!='\t')

答案 1 :(得分:1)

而不是使用printf try putchar,也可以按照上面的评论,使用&amp;&amp;而不是||。

这是我的代码 -

#include<stdio.h>

main()
{
    int c, nw;                  /* nw for word & c for character*/

    while ( ( c = getchar() ) != EOF ){

    if ( c != ' ' && c != '\n' && c != '\t')
    nw = c;
    else {
        nw = '\n';
    }

    putchar (nw);

    }

}

此代码将为您提供所需的输出

答案 2 :(得分:0)

如果您希望strtok库中的string.h函数可以通过提供分隔符将输入切换为多个单词,则可以使用。

这是一个完美的代码评论,可以满足您的需求

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

int main(int argc, char *argv[])
{
    char line[1000]=""; // the line that you will enter in the input
    printf("Input the line:\n>>");
    scanf("%[^\n]",line); // read the line till the you hit enter button
    char *p=strtok(line," !#$%&'()*+,-./'"); // cut the line into words 
    // delimiter here are punctuation characters  (blank)!#$%&'()*+,-./'

    printf("\nThese are the words written in the line :\n");
    printf("----------------------------------------\n");
    while (p!=NULL) // a loop to extract the words one by one 
    {
        printf("%s\n",p); // print each word
        p=strtok(NULL," !#$%&'()*+,-./'"); // repeat till p is null 
    }

    return 0;
}

如果我们执行上面的代码,我们将获得

Input the line:
>>hello every body how are you !

These are the words written in the line :
----------------------------------------
hello
every
body
how
are
you

答案 3 :(得分:0)

suggest the code implement a state machine, 
where there are two states, in-a-word and not-in-a-word.  
Also, there are numerous other characters that could be read 
(I.E. ',' '.' '?' etc) that need to be check for. 

the general logic:

state = not-in-a-word
output '\n'

get first char
loop until eof
    if char is in range a...z or in range A...Z
    then 
        output char
        state = in-a-word
    else if state == in-a-word
    then
         output '\n'
         state = not-in-a-word
    else
         do nothing
    end if
    get next char
end loop

output '\n'

答案 4 :(得分:0)

我认为简单的解决方案就像

#include <stdio.h>

int main(void) {
    // your code goes here
    int c;
    while((c=getchar())!=EOF)
    {
        if(c==' ' || c=='\t' || c=='\b')
        {
            printf("\n");
            while(c==' ' || c=='\t' || c=='\b')
            c=getchar();
        }
        if(c!=EOF)
        putchar(c);
    }
    return 0;
}