我得到一个任务。我必须编写一个由几个函数组成的程序来分析文本(计算单词、符号、行数,而不是白色符号等)这是我的程序:
#include <stdio.h>
#include <stdlib.h>
int allSigns(char text[])
{
int i;
for (i = 0; text[i] != '\0'; ++i);
return i;
}
int notWhiteSigns(char text[])
{
int sum;
for (int i = 0; text[i] != '\0'; ++i)
{
if (text[i] != (' ' && '\n' && '\t'))
sum++;
}
return sum;
}
int words(char text[])
{
int i;
int sum = 0;
for (int i = 1; text[i] != '\0'; ++i)
{
if (text[i] == ' ' && text[i-1] && text[i] != ('\t' && '\n'))
sum++;
}
if (text[i-1] != ' ');
sum++;
return sum;
}
int lines(char text[])
{
int i;
int sum = 1;
for (int i = 0; text[i] != '\0'; ++i)
{
if (text[i] == '\n')
sum++;
}
return sum;
}
int main (int argc, char *argv[])
{
char sentence[] = "C is \n a \n programming \t language";
printf("Show array: %s \n", sentence);
printf("All signs: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的输出是:
Show array: C is
a
programming language
All signs: 33
not white signs: 66
words: 8
lines: 3
Run Code Online (Sandbox Code Playgroud)
我看到我犯了一些错误。线路没问题(3)。但我有8 个字而不是5 个字。计算所有单词的函数是可以的(我将 \n 和 \t 算作一)。我不知道为什么我有66 个“非白色标志”(除 ' '、'\n'、'\t' 之外的所有标志)我应该有 23 个
错误在这里:
if (text[i] != (' ' && '\n' && '\t'))
Run Code Online (Sandbox Code Playgroud)
中的每个字符(' ' && '\n' && '\t')都将表示为 ASCII 代码。所以这个表达式的意思是(text[i] != (32 && 10 && 9)).
试试这个:
if ((text[i] != ' ') && (text[i] != '\n') && (text[i] != '\t'))
Run Code Online (Sandbox Code Playgroud)
您还应该sum在使用前初始化变量。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |