我对此很陌生,所以我坚持做一些可能非常简单的事情。
在这个程序中,我试图将每个单词从一个数组分成二维数组,以及任何句号,逗号或分号。但是,它仅在一行中重新打印该句子。我做了几个测试,似乎第一个for循环从不识别空格,逗号,句号或分号。有人可以帮忙吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char wordProblem[1024];
char wordProblemWords[200][20];
printf("Please enter a word problem.\n");
fgets ( wordProblem, 1024, stdin );
int length = strlen (wordProblem);
int i;
int wordNumber = 0;
int letterOfWord = 0;
for ( i = 0; i < length; i++){
if (wordProblem[i]==" ") {
++wordNumber;
letterOfWord = 0;
}else if (wordProblem[i]=="." || wordProblem[i]=="," || wordProblem[i]==";"){
++wordNumber;
letterOfWord = 0;
wordProblemWords[wordNumber][letterOfWord] = wordProblem[i];
wordNumber;
letterOfWord = 0;
}else{
wordProblemWords[wordNumber][letterOfWord] = wordProblem[i];
++letterOfWord;
}
}
int j;
for (j = 0; j <= wordNumber; j++){
printf("%s", wordProblemWords[j]);
printf("\n");
}
return 0;
}
编辑:我已经改变了程序,问题解决了。如果你想纠正任何其他问题(我确定有吨)这里是新代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>//based on what user3629249 said
int main()
{
char wordProblem[1024];
char wordProblemWords[200][20];
printf("Please enter a word problem.\n");
fgets ( wordProblem, 1024, stdin );
int length = strlen (wordProblem);
int i;
int wordNumber = 0;
int letterOfWord = 0;
for ( i = 0; i <= length; i++){
if (wordProblem[i]==' ') { //single quotes instead of double (tivn)
wordProblemWords[wordNumber][letterOfWord] = '\0';//added this to have a null at the end of the string, removes gibberish
++wordNumber;
letterOfWord = 0;
}else if (wordProblem[i]=='.' || wordProblem[i]==',' || wordProblem[i]==';'){
++wordNumber;
letterOfWord = 0;
wordProblemWords[wordNumber][letterOfWord] = wordProblem[i];
wordProblemWords[wordNumber][letterOfWord] = '\0'//again to remove gibberish
}else{
wordProblemWords[wordNumber][letterOfWord] = wordProblem[i];
++letterOfWord;
}
}
int j;
for (j = 0; j <= wordNumber; j++){
printf("%s", wordProblemWords[j]);
printf("\n");
}
return 0;
}
答案 0 :(得分:2)
您需要使用单引号来比较单个字符。双引号意味着字符串。
if (wordProblem[i]==' ') {
++wordNumber;
letterOfWord = 0;
} else if (wordProblem[i]=='.' || wordProblem[i]==',' || wordProblem[i]==';'){
...
另请注意,fgets
将在结果中包含换行符。