基本上我们提供了主要功能:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
{
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1)break;
}}
我们不要改变那个
我们必须创建函数getword(),它应该包含一个读取字符的循环
将它存储在一个接一个地提供的地址中的数组中,它应该停在空白处(tab,space,eof)
基本上我有这个:
int getword(char *w)
{
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n");
gets(str);
/*this was provided by the professor, but i'm not sure how to use it
while (( iochar - getchar()) !=EOF);
*/
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
return 0;}
现在该程序的输出是:
enter your sentence:
hey stockoverflow
your string: 'hey stockoverflow' contains 16 of letters
n=0, s=[]
所以我正在保存字符串并对其进行计数,但我并没有将它存储在应该存在的位置。
它应该显示n = 16,s = [hey stockoverflow]
实际上它应该显示n = 3,s = [嘿]
任何帮助将不胜感激
答案 0 :(得分:0)
这可能是您正在寻找的:
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
else
{
str[i] = '\0'; // Terminate str
break; // Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
strcpy(w, str); // Add this line to copy str into w (which is s from main)
return strlen(w); // Return the length of the result string