读字直到行尾

时间:2012-08-25 18:07:40

标签: c scanf

  

可能重复:
  Any cool function to replace readln from pascal in ansi c?

我多次遇到过如何读到单词到行尾的问题?
例如:
2
hello this is a word
hi five
so i want to output
case 1:
hello
this
is
word
case 2:
hi
five

3 个答案:

答案 0 :(得分:1)

当您遇到\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
}

通过这种方式,您可以准确选择新行时要执行的操作。在解析文件时,我倾向于使用这种方法,我将每一行写入缓冲区,处理缓冲区,然后开始将下一行移动到缓冲区中进行处理。

答案 1 :(得分:-1)

其中一个危险功能将为您提供名为gets的解决方案。

否则: -

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

答案 2 :(得分:-1)

#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;
}
相关问题