【发布时间】:2015-12-14 12:16:51
【问题描述】:
这是我下面的代码,它的作用是将输入输入到变量 string1 中,然后我的 while 循环标记每个单词,我能够达到我的任务目标,即反转字符串中的单词。我的代码下面是它的输出,如您所见,没有空格。如何在最终字符串中添加与原始字符串相似的空格?
代码:
int main()
{
int ch, ss=0, s=0;
char x[3];
char *word, string1[100], string2[100], temp[100]={0};
x[0]='y';
while(x[0]=='y'||x[0]=='Y')
{
printf("Enter a String: ");
fgets(string1, 100, stdin);
if (string1[98] != '\n' && string1[99] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
word = strtok(string1, " \n");
while(word != NULL)
{
s = strlen(word);
ss=ss+s;
strncpy(string2, word, s+1);
strncat(string2, temp, ss);
strncpy(temp, string2, ss+1);
printf("string2: %s\n",temp);
word = strtok(NULL, " \n");
}
printf("Run Again?(y/n):");
fgets(x, 2, stdin);
while ( (ch = fgetc(stdin)) != EOF && ch != '\n');
}
return 0;
}
输出:
Enter a String: AAA BBB CCC
string2: AAA
string2: BBBAAA
string2: CCCBBBAAA
【问题讨论】:
-
if (string1[98] != '\n' && string1[99] == '\0')未定义如果fgets()返回NULL或读取少于 98 个字符。 -
没有空格,因为你不附加空格!!
-
另外,
strncpy(string2, word, s+1); strncat(string2, temp, ss); strncpy(temp, string2, ss+1);序列实际上保证了temp最终将没有空终止符。
标签: c string append whitespace strcat