gpt4 book ai didi

c - 如何将数组存储在地址C中

转载 作者:行者123 更新时间:2023-11-30 17:05:50 26 4
gpt4 key购买 nike

基本上我们提供了主要功能:

 #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(),它应该包含一个读取字符的循环,

将其一一存储在提供的地址中的数组中,并且应该因空格(制表符、空格、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=[hey]

如有任何帮助,我们将不胜感激

最佳答案

这可能就是您正在寻找的:

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

关于c - 如何将数组存储在地址C中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35047450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com