【问题标题】:C - I/O - Array of chars to print out sentence structureC - I/O - 打印句子结构的字符数组
【发布时间】:2014-03-12 17:33:04
【问题描述】:

所以我正在接受这样的文本文件:

Hello. This is my test! I need to print sentences.
Can I do it? Any help is welcomed. Thanks!

我正在尝试输出:

1. Hello.
2. This is my test!
3. I need to print sentences.
4. Can I do it?
...and so on....

这是我目前所写的:

#include <stdio.h>
#include <stdlib.h>
  main() {
     int storage[50];
     int i = 0 ;
     int linecount = 1 ;
     char c;

     for (;;) {
      c=getchar();
      if(c == '\n'){
        c == '\0';}
      storage[i] = c;
      i++;

      if (c == '.' || c == '!' || c == '?') {
        int j ;
        printf("%d. ", linecount++);
        for (j = 0; j < i; j++) {
         printf("%c", storage[j]); }
        i = 0 ;
        printf("\n");
      }
   }
 }

结果是输出:

1. Hello.
2.  This is my test!
3.  I need to print sentences.
4. 
Can I do it?
5.  Any help is welcomed.
6.  Thanks!

我的第一个问题是它为第 4 行打印了一个 '\n',我认为我的代码:

if(c == '\n'){
  c == '\0';}

会解决这个问题,但事实并非如此。

我的第二个问题是它在第一条记录之后添加了一个额外的空格字符。 我知道这是因为我使用了 print 语句:

"%d. "

而且句子的开头也有一个空格与最后一句分开,但我不确定如何解决这个问题。任何帮助都会很棒!谢谢! -qorz

【问题讨论】:

标签: c arrays io char


【解决方案1】:

您的第一个问题出现是因为您需要使用= 运算符,而不是==。您实际上是在测试该值,而不是将数组位置更改为 \0

要解决这个问题,请更改

if(c == '\n'){
    c == '\0';
}

if(c == '\n'){
    c = '\0';
}

关于第二个问题,请看here

【讨论】:

    【解决方案2】:

    这里==不是赋值运算符,改成=

    if(c == '\n'){
       c = '\0'; 
    }
    

    【讨论】:

      【解决方案3】:
      #include <stdio.h>
      #include <stdlib.h>
      #include <ctype.h>
      
      int main() {
          int storage[50];
          int i = 0 ;
          int linecount = 1 ;
          int c;
      
          while(EOF!=(c=getchar())) {
              storage[i++] = c;
              if (c == '.' || c == '!' || c == '?') {
                  int j ;
                  printf("%d. ", linecount++);
                  for (j = 0; j < i; j++) {
                      printf("%c", storage[j]);
                  }
                  printf("\n");
                  i = 0 ;
                  while(isspace(c=getchar()))
                      ;//skip white spaces
                  ungetc(c, stdin);
              }
          }
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 2021-04-27
        • 1970-01-01
        相关资源
        最近更新 更多