每行打印一个字

printing a word per line

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

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

逻辑很简单。我检查输入是否不是换行符、制表符或 space,如果是,则打印它,否则打​​印换行符。

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

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

它打印了整个东西。这里出了什么问题?

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

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

如果你想要 string.h 库中的 strtok 函数,你可以使用它,它可以通过提供分隔符将输入分成许多单词。

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

#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
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'

不要使用 printf 试试 putchar,同样按照上面的评论,您应该使用 && 而不是 ||。

这是我的代码-

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

    }

}

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

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

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