所以我正在接收一个像这样的文本文件:
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
最佳答案
出现第一个问题是因为您需要使用 =
运算符,而不是 ==
。您实际上是在测试该值,而不是将数组位置更改为 \0
。
要解决此问题,请更改
if(c == '\n'){
c == '\0';
}
至
if(c == '\n'){
c = '\0';
}
对于你的第二个问题,请看 here .
关于C - I/O - 用于打印句子结构的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22359442/