【问题标题】:Reading words till the end of line [duplicate]阅读单词直到行尾[重复]
【发布时间】:2012-08-25 18:07:40
【问题描述】:

可能重复:
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

【问题讨论】:

    标签: c scanf


    【解决方案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
    }
    

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

    【讨论】:

      【解决方案2】:

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

      否则:-

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

      【讨论】:

        【解决方案3】:
        #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;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-06
          • 1970-01-01
          • 2021-01-29
          • 2020-07-23
          • 2022-01-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多