【问题标题】:Unable to append a whitespace to a string in while loop无法在while循环中将空格附加到字符串
【发布时间】: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


【解决方案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;
}

【讨论】:

  • 感谢您的回答。我工作。虽然,你能告诉我为什么它有效。我不明白我的程序在做什么。
猜你喜欢
  • 2017-02-11
  • 1970-01-01
  • 2018-09-25
  • 2020-09-09
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
相关资源
最近更新 更多