无法在while循环中向空格附加空格

时间:2015-09-17 14:55:45

标签: c string append whitespace strcat

这是我下面的代码及其作用,将输入转换为变量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

1 个答案:

答案 0 :(得分:1)

如何简单地添加空格?

#include <stdio.h>
#include <string.h>

int main()
{
  int ch, ss=0, s=0;
  char x[3];
  char *word, string1[100]={0}, string2[200], temp[200]={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;

      /* copy the word to the working buffer */
      strncpy(string2, word, s+1);
      /* if this is not the first word, put a space after the word */
      if (temp[0] != '\0') strcat(string2, " "); /* add this */
      /* concat the previously read words after the new word and a space */
      strncat(string2, temp, ss);
      /* adjust the length of the string for the added space */
      ss++; /* add this for space */
      /* copy the new result to temp */
      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;
}