2016-02-19 37 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搞砸了! –

相關問題