我必须编写一个程序,输入是:
Spring Miles 独立谎言自我
结果将是: 微笑
但是我的输入有一些问题。我不知道输入的长度,所以可以是任意长度。
这就是为什么我使用 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 循环运行 10 次,您的代码将定义 10 个 char 数组,但在 while 循环完成后其中一个可用。以下是我的代码
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也许可以帮助你。 Malloc是C中的一个函数。您可以使用它来管理您的主内存。
ch
是char
。这里将数字1
添加到字符“空格”是没有意义的。相反,您必须从字符串中读取下一个字符。你可以这样做:
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 有点陌生,所以我强烈建议你把它画出来,以确保你理解它是如何工作的。