,所以我必须编写一个程序,其中输入为:
春季英里独立谎言ego
的结果将是:微笑
但是我在输入方面有一些问题。我不知道输入的Lenght,因此可以是任何lenght。
这就是为什么我使用scanf读取每个字符的原因。我数量的空间要知道我要保存所需字符的数组的大小。
所以在这些之后,这是我的主要问题:如果我找到了一个空间,我应该保存我从scanf读到的下一个角色,但是我该怎么做?还是你们知道解决此问题的其他选择?
到目前为止,这是我的代码:
int main()
{
char ch;
int i = 0, count= 0;
while(scanf("%c", &ch) != EOF)
{
if(ch == 'n')
count = 0;
if(ch == ' ')
count++;
char array[count+1];
if(ch == ' ')
array[i++] = ch + 1; // I tried this, but it doesn't work.
}
return 0;
}
如果您在while循环中定义char数组,则将永远不会可用。如果while loop运行10次,您的代码将定义10个char数组循环完成。
int main() {
char ch;
char array[1024];
int i = 0, count= 0;
int status = 1;
while(scanf("%c", &ch) != EOF) {
if(ch == 'n') {
break;
}
if(ch == ' ') {
status = 1;
continue;
}
if (status == 1) {
status = 0;
array[i++] = ch;
}
}
array[i++] = ' ';
printf("%s", array);
return 0;
}
我的代码是基于以下假设:数组长度的长度不会超过1024。我们不知道输入的时间长度,然后再输入。malloc是C.您可以使用它来管理您的主内存。
ch
是 char
。在这里将数字1
添加到字符" Space"上是没有意义的。相反,您必须从字符串中读取下一个字符。您可以这样做:
int main()
{
char ch;
bool had_space;
int i = 0, count= 0;
had_space = true;
while(scanf("%c", &ch) != EOF)
{
if(ch == 'n')
count = 0;
if(ch == ' ')
count++;
char array[count+1];
if(ch == ' ')
had_space = true;
else if (had_space)
array[i++] = ch;
}
return 0;
}
我想您还必须定义循环外部的数组。
如果您的输入确实是不明的,并且您不知道它将包含多少个空间,则需要动态内存分配 - 这意味着您根据需要分配内存而不是试图将其粘在堆栈上的固定尺寸内存中。有几种方法,但我认为简单的链接列表是最干净的。以下应执行您需要的事情:
typedef struct linkedListNode {
char ch;
struct linkedList * next;
} linkedListNode_t;
linkedListNode_t *pHead = NULL;
linkedListNode_t **ppNext = &pHead;
// pHead points to the first node in the list
// ppNext points to the pointer to the next element in the list
while(scanf("%c", &ch) != EOF) {
if (ch == ' ') {
// scan next character, and add to linked list:
if (scanf("%c", &ch) == EOF)
break; // exit loop if we've hit end of input
// ch is ok -- add to list:
// allocate a new pNode to store the information
linkedListNode_t *pNode = malloc(sizeof(linkedListNode_t);
if (pNode == NULL) {
printf("Out of memory -- aborting");
exit (-1); // if allocation failed, abort program
}
pNode->ch = ch;
pNode->next = NULL;
*ppNext = pNode; // make previous node point to this one.
ppNext = &pNode->next; // update ppNext
}
else if (ch == 'n') {
// special handling of newline -- did you want to print the
// string and dump memory here?
}
} // end wile loop
// at this point we have a linked list with all characters that
// follow spaces -- print it out:
linkedListNode *pNode = pHead;
while (pNode != NULL) {
printf("%c", pNode->ch);
pNode = pNode->next;
}
printf("n");
// free list:
pNode = pHead;
linkedListNode *pNext;
while (pNode) {
pNext = pNode->pNext;
free(pNode);
pNode = pNext;
}
免责声明:我尚未测试上述内容,因此我可能犯了语法错误。无论如何,您看起来对C有些新奇,因此我强烈建议您将其提出来,以确保您了解它的工作原理。