计算给定句子中组成单词的字母
我正在尝试编写一个程序来查找给定句子中存在多少个 1 个字母、2 个字母、3 个字母、4 个字母的单词,我终于想出了一些代码。然而,有一个问题。代码已经成功编译,但是当运行时,程序失败并退出,没有任何结果。
int main( void )
{
char *sentence = "aaaa bb ccc dddd eee";
int word[ 5 ] = { 0 };
int i, total = 0;
// scanning sentence
for( i = 0; *( sentence + i ) != '\0'; i++ ){
total = 0;
// counting letters in the current word
for( ; *( sentence + i ) != ' '; i++ ){
total++;
} // end inner for
// update the current array
word[ total ]++;
} // end outer for
// display results
for( i = 1; i < 5; i++ ){
printf("%d-letter: %d\n", i, word[ i ]);
}
system("PAUSE");
return 0;
} // end main
I am trying to write a program to find how many 1-letter, 2-letter, 3-letter, 4-letter words exist in a given sentence, and I have finally come up with some code. However, there is a problem. The code has been successfully compiled, but when it comes to running, the program fails and quits with no result.
int main( void )
{
char *sentence = "aaaa bb ccc dddd eee";
int word[ 5 ] = { 0 };
int i, total = 0;
// scanning sentence
for( i = 0; *( sentence + i ) != '\0'; i++ ){
total = 0;
// counting letters in the current word
for( ; *( sentence + i ) != ' '; i++ ){
total++;
} // end inner for
// update the current array
word[ total ]++;
} // end outer for
// display results
for( i = 1; i < 5; i++ ){
printf("%d-letter: %d\n", i, word[ i ]);
}
system("PAUSE");
return 0;
} // end main
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你在最后一个词之后出现了段错误。当到达空终止符时,内部循环不会终止。
其他评论:为什么最后要调用
system("PAUSE")
?确保使用您使用的库的-Wall
和#include
标头进行编译。即使它们是标准库的一部分。You're segfaulting after the last word. The inner loop doesn't terminate when it gets to the null terminator.
Other comments: Why call
system("PAUSE")
at the end? Make sure you compile with-Wall
and#include
headers for the libraries you use. Even if they're part of the standard library.