鱼C论坛

 找回密码
 立即注册
查看: 2293|回复: 1

对于字符串后面'\n','\0';不是很清楚

[复制链接]
发表于 2012-1-24 02:51:59 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
/* Program 7.13 Generalizing string input */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const size_t BUFFER_LEN = 128;              /* Length of input buffer    */
const size_t NUM_P = 100;                   /* maximum number of strings */
int main(void)
{
  char buffer[BUFFER_LEN];                  /* Input buffer             */
  char *pS[NUM_P] = { NULL };               /* Array of string pointers */
  char *pbuffer = buffer;                   /* Pointer to buffer        */
  int i = 0;                                /* Loop counter             */
  printf("\nYou can enter up to %u messages each up to %u characters.",
                                                  NUM_P, BUFFER_LEN-1);
  for(i = 0 ; i<NUM_P ; i++)
  {
    pbuffer=buffer ; /* Set pointer to beginning of buffer */
    printf("\nEnter %s message, or press Enter to end\n",
                                                           i>0? "another" : "a");
    /* Read a string of up to BUFFER_LEN characters */
    while((pbuffer - buffer < BUFFER_LEN-1) &&
           ((*pbuffer++ = getchar()) != '\n'));
    /* check for empty line indicating end of input */
    if((pbuffer - buffer) < 2)
      break;
    /* Check for string too long */
    if((pbuffer - buffer) == BUFFER_LEN && *(pbuffer-1)!= '\n')这里用‘\0'呢有什么区别
    {
      printf("String too long - maximum %d characters allowed.",
                                                      BUFFER_LEN);
      i--;
      continue;
    }
    *(pbuffer - 1) = '\0';                  /* Add terminator             */
    pS[i] = (char*)malloc(pbuffer-buffer);  /* Get memory for string      */
    if(pS[i] == NULL)  
  {                              
   
      printf("\nOut of memory - ending program.");
      return 1;                           
    }
    /* Copy string from buffer to new memory */
    strcpy(pS[i], buffer);
  }
  /* Output all the strings */
  printf("\nIn reverse order, the strings you entered are:\n");
  while(--i >= 0)
  {
     printf("\n%s", pS[i] );                /* Display strings last to first */
     free(pS[i]);                           /* Release the memory we got     */
     pS[i] = NULL;                    /* Set pointer back to NULL for safety */
  }
  return 0;
}




                               
登录/注册后可看大图
该贴已经同步到 空手套小白狼的微博
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-1-24 13:59:48 | 显示全部楼层
  1. #include <stdio.h>



  2. void main()
  3. {
  4.         char *a="abcde\nfghijkl";
  5.    
  6.         char *b="abcde\0fghijkl";

  7.     printf("%s,%s",a,b);
  8.    
  9. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-10 22:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表