C 读单词直到行尾

C 读单词直到行尾,c,scanf,C,Scanf,可能重复: 我曾多次遇到一个问题,那就是如何把单词读到行尾? 例如: 2. 你好,这是一个单词 你好,五位 所以我想输出 案例1: 你好 这 是 单词 案例2: 你好 五个其中一个危险函数将为您提供名为gets的解决方案 否则:- char line[512]; int count=0; char input=1; while((input=getchar())!='\n') line[count++]=input; 当遇到\n或\r字符时,可以循环遍历字符串中的每个字符。也许是这样

可能重复:

我曾多次遇到一个问题,那就是如何把单词读到行尾? 例如: 2. 你好,这是一个单词 你好,五位 所以我想输出 案例1: 你好 这 是 单词 案例2: 你好
五个

其中一个危险函数将为您提供名为gets的解决方案

否则:-

char line[512];
int count=0;
char input=1;
while((input=getchar())!='\n')
    line[count++]=input;

当遇到\n或\r字符时,可以循环遍历字符串中的每个字符。也许是这样吧

char str[] = "Hello this is a word\nhi five";
int i;

for(i = 0; str[i] != '\0'; i++)
{
    if(str[i] != '\n' && str[i] != '\r') //do something with str[i]
    else //do something if a new line char is found
}
通过这种方式,您可以准确地选择在出现新线路时要执行的操作。我在解析文件时经常使用这种方法,我将每一行写入缓冲区,处理缓冲区,然后开始将下一行移动到缓冲区中进行处理

#include <stdio.h>

int main(){
    int i, dataSize=0;

    scanf("%d%*[\n]", &dataSize);
    for(i = 1; i<=dataSize;++i){
        char word[64];
        char *p=word, ch=0;
        printf("case %d:\n", i);
        while(EOF!=ch && '\n'!=ch){
            switch(ch=getchar()){
              case ' '://need multi space char skip ?
              case '\t':
              case '\n':
              case EOF:
                *p = '\0';
                printf("%s\n", p=word);
                break;
              default:
                *p++ = ch;
            }
        }
        if(ch == EOF)break;
    }

    return 0;
}

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

int main(){
    int i, dataSize=0;

    scanf("%d%*[\n]", &dataSize);
    for(i = 1; i<=dataSize;++i){
        char word[64],ch = 0;
        int stat = !EOF;
        printf("case %d:\n", i);
        while(EOF!=stat && '\n'!=ch){
            ch = 0;
            stat=scanf(" %s%c", word, &ch);
            if(EOF!=stat || isspace(ch)){
                printf("%s\n", word);
            }
        }
        if(EOF==stat)break;
    }

    return 0;
}