2016-02-19 89 views
-1

我不能为了我的生活找出为什么我的代码没有产生我需要的输出。要求是不使用任何功能。当我输入一行像“文本”这样的文本时,得到的数组是“tex”,切断了对我来说毫无意义的最后一个字母。接收用户输入并将其存储在一个数组中C

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

int read_input(char line_of_text[]) 
{ 
     int index = 0; 
     char ch; 
//  if(!line_of_text[0]) 
//    return index; 
     for(ch = getchar(); ch != '\n' && ch != '\0'; ch = getchar()){ 
       if(ch == EOF){ //clear string and return EOF 
         line_of_text[0] = '\0'; 
         return EOF; 
       } 
       line_of_text[index++] = ch; 

     } 
     line_of_text[++index] = '\0'; 
     return index; 
} 
+1

'炭CH;' - >'INT CH = 0;'' –

+1

line_of_text [++指数] = '\ 0';' - >'line_of_text [index] ='\ 0 ';' – jiveturkey

+1

为什么在到达EOF时清除了字符串? –

回答

1

将所有的意见,并清理逻辑

注意水平和垂直间距如何使代码更易于阅读/理解

通知内容不使用任何“边后效应来处理的增量 '索引' 变量

int read_input(int max_chars, char line_of_text[]) 
{ 
    int index = 0; 
    int ch = 0; // getchar() returns an int, not a char 

    // Note: initialization of 'index' handled in declaration 
    // Note: '-1' to leave room for NUL termination char 
    for(; index < (max_chars-1); index++) 
    { 
     ch = getchar(); 

     // Note: place literal on left so compiler can catch `=` error 
     if(EOF == ch || '\n' == ch || '\0' == ch) 
     { 
      break; 
     } 

     // acceptable char so place into buffer 
     line_of_text[index] = ch; 
    } 

    // when done, terminate the char string 
    line_of_text[index] = '\0'; 

    return index; 
} // end function: read_input 
+0

谢谢我认为这是char,而不是一个int搞砸了! –

相关问题