2012-12-02 91 views
2

我写了一个函数,它读取一个未知长度的字符串,直到Enter被按下并返回一个字符指针。当我从开关柜内调用该功能时,它不会等待我的输入。为什么我的功能不等待输入?

char *get_paths() 
{ 
    unsigned int length_max = 256; /*Initial length of string*/ 
    unsigned int current_size; 
    current_size = length_max; 

    /* Allocating memory for string input */ 
    char *tmpStr = malloc(length_max); 

    /* Simple check to make sure our pointer is not NULL */ 
    if(tmpStr != NULL) 
    { 
     int c = EOF; 
     unsigned int i = 0; 

     printf("Enter The EXACT or RELATIVE File Paths Separated by a Space: "); 

     /* Accept input until Enter key is pressed or user inserts EOF */ 
     while((c = getchar()) != '\n' && c != EOF) 
     { 
      tmpStr[i] = (char)c; 
      ++i; 

      /* If memory is filled up, reallocate memory with bigger size */ 
      if(i == current_size) 
      { 
       current_size = i + length_max; 
       /* realloc does magic */ 
       tmpStr = realloc(tmpStr, current_size); 
      } 
     } 

     /* A valid string always end with a '\0' */ 
     tmpStr[i] = '\0'; 
     printf("Got it: %s \n", tmpStr); /*TODO: REMOVE;; USED FOR TESTING*/ 
     return tmpStr; 
    } 
} 

开关壳体(I有一个char * PTR = NULL出开关块):

/*File input*/ 
case 1: 
    ptr = get_filepaths(); 
break; 

输出:

输入确切或RELATIVE文件路径分隔的空间:明白了:

+0

哪里是你的交换机的情况下 –

+0

好你的注释你的代码,但是你的一些评论是非常多余的,比如“简单的检查,以确保我们的指针不为NULL”是显著长于'如果(tmpStr! = NULL)',并且它没有解释代码没有解释的任何东西。 – dreamlax

回答

-1

我能够找到'解决办法'的解决方案就是在第一个printf()调用后面添加一个getchar()不知道为什么这个工程!

+0

你可能有一个'scanf()'的地方留下换行符([阅读此](http://c-faq.com/stdio/scanfinterlace.html))。你应该在那里清理,而不是在'get_paths()'函数内部清理。 – potrzebie

2

你很可能遇到stdout缓冲问题,这是printf的默认设置。您需要明确清空stdout或在您的第一个printf语句末尾放置一个换行符以强制缓冲区刷新。由于在“Got it”语句末尾有一个换行符,会发生什么情况是两个语句(第一个语句被缓冲)会同时输出到输出,因为第二个语句会强制刷新缓冲区。

另一种可能性是,有可能已在stdin未读数据,当你调用在while -loop getchar(),它读取以前的缓存数据,打一个换行符,然后退出循环,而不是让你来输入新的信息。为了避免这个问题,请执行如scanf("%*[^\n]%*c");这样的操作,以便将输入消耗到输入中已经存在的下一个换行符(包括换行符本身),而不用担心缓冲区溢出。

+0

在第一次printf调用后添加fflush(stdout),不起作用。添加\ n到printf,没有工作。 :( – Nima

+0

你在调用'getchar()'之前清除了输入吗?换句话说,可能在'stdin'上有一些其他的输入正在被读取吗? – Jason

+0

以及我用scanf在另一个函数中读取用户输入的顺序使用开关,我试着在调用getchar()之前添加'fflush(stdin)',但仍然跳过输入。 – Nima