我的程序假设接受字符串并在单独的行上打印每个字符串。我正在寻找空间来决定何时将单词打印到新行。我使用一个名为 hold 的字符串来存储每个字母,直到找到一个空格。然后这个词被打印到屏幕上。我遇到的问题是,如果保留的最后一个单词比前一个单词长,那么新单词将在最后一个单词的尾部打印。
示例:如果最后一个单词是“Program”而下一个单词是“cat”,则屏幕输出将是 Program 后跟 catgram。
下面是我的代码:
#include<stdio.h>
#include<string.h>
char *string;
char *hold;
int main(void)
{
string = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
printf("please enter a string\n");
scanf("%[^\n]",string);
while (string[i] !='\o')
{
if (string[i] !=' ')
{
hold[j] = string[i];
j++;
}
else
{
printf("%s\n",hold);
j = 0;
}
i++;
}
return 0;
free(string);
}
最佳答案
请添加行
hold[j]='\0';
原因:字符串的末尾是 '\0' 如果您没有显式添加 '\0' 它将占用整个字符串,直到找到第一个 '\0' 和
printf("%s\n",hold);
原因:要打印最后一个单词,如果单词字符串不以空格结尾
在下面编辑的程序中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *string;
char *hold;
int main(void)
{
string = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
printf("please enter a string\n");
scanf("%[^\n]",string);
printf("%s\n",string);
while (string[i] !='\0')
{
if (string[i] !=' ')
{
hold[j] = string[i];
j++;
}
else
{
hold[j]='\0'; **//Edited here**
printf("%s\n",hold);
j = 0;
}
i++;
}
printf("%s\n",hold); **//Edited here**
return 0;
free(string);
}
关于c - 我似乎无法清除用于临时保存文本 block 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39676665/