2016-11-23 63 views
-2

需要阅读的一切,直到发言权***出现:如何读取串多行,直到指定的字符用C

输入:

Hey there 
how are 
you 
*** 

输出:

Hey there 
how are 
you 

会已使用scanf("%[^***]s),但无法一次读取所有行。只有那些具有基本的C知识

+3

逐行阅读?? –

+4

阅读['fgets'](http://en.cppreference.com/w/c/io/fgets)和['strcmp'](http://en.cppreference.com/w/c/string/字节/的strcmp)。请注意'fgets'可以在缓冲区中添加换行符。 –

+0

还没研究strcmp – Ashish

回答

1

我会做到这一点的方式是一次读取一行(有一个函数,如fgets代替scanf函数),然后看你最后一次读等于***行。您可以使用使用strcmp来做到这一点,但如果您由于某种原因不允许使用strcmp,您也可以手动执行此操作。

0

要跳过一个,两个或四个或更多星号但停在三个星号上,您一次只能读取一个字符的输入流。移动数组以放弃第一个字符并将最近的字符添加到结尾。然后在读取一个字符后,将输入数组与数组进行比较以匹配。要允许处理继续四个或更多星号,找到三个匹配的星号,请读取另一个字符并使用ungetc将字符放回到适当的流中。

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

int main(void) { 
    char input[4] = ""; 
    char match[4] = "***"; 
    int result = 0; 
    int last = 0; 
    int prior = 0; 

    while ((result = fgetc (stdin)) != EOF) {//read each character from stream 
     prior = input[0];//the fourth character back 
     if (prior == '*') { 
      fputc (prior, stdout); 
     } 
     //shift the array 
     input[0] = input[1]; 
     input[1] = input[2]; 
     input[2] = result;//add the new character 
     input[3] = '\0'; 
     if (!input[0] && result != '\n') {//until a character is shifted into input[0] 
      if (result != '*') { 
       fputc (result, stdout); 
      } 
      continue; 
     } 
     if (strcmp (input, match) == 0) {//the three characters match 
      if ((last = fgetc (stdin)) != EOF) {//read another character 
       if (last == '*') {//to skip more than three * 
        ungetc (last, stdin);//put back into stream 
       } 
       else { 
        if (prior != '*') { 
         break; 
        } 
        else { 
         ungetc (last, stdin); 
        } 
       } 
      } 
      else { 
       fprintf (stderr, "problem getting input\n"); 
       return 1; 
      } 
     } 
     if (result != '*') { 
      //print pending asterisks as needed 
      if (input[0] == '*') { 
       fputc (input[0], stdout); 
       input[0] = ' '; 
      } 
      if (input[1] == '*') { 
       fputc (input[1], stdout); 
       input[1] = ' '; 
      } 
      if (input[2] == '*') { 
       fputc (input[2], stdout); 
       input[2] = ' '; 
      } 
      fputc (result, stdout); 
     } 
    } 
    fputc ('\n', stdout); 
    return 0; 
} 
相关问题