[英]printf limited to three characters?
我已經將此函數精簡為導致問題的原因,但是我將嘗試為該問題提供足夠的上下文,而又不要使您細讀行與行:
基本上,我將字符串輸入下面的函數中,如果字符串中的第一個字符是#,那么我想打印該字符串。 而已。
但是,這樣做時,打印出的字符串被切成三個字符的長度。 因此,例如,在輸入字符串為“ #Hello,World! ”的情況下,僅會打印“ #H ”。
我從以下輸入文件中使用fgets()獲取輸入字符串:
#測試
#######
# 更多
輸出如下:
#T
###
###
#
#M
以下是相關的調整后功能:
int main(int argc,char *argv[]){
FILE *input;
lineResponse response;
//If a filename was specified, the file exists, and it is openable
if(argv[1] != NULL && (input = fopen(argv[1],"r")) != NULL){
char *currentLine = "";
//Loop through the lines
while(fgets(currentLine,sizeof(input),input)){
response = parseLine(currentLine);
}
}
fclose(input);
getchar();
}
lineResponse parseLine(char *line){
lineResponse response = {0,NULL}; //0 is the default lineType, denoting a line that cannot be parsed
if(line != NULL){
if(line[0] == '#'){
printf("%s\n",line);
}
}
return response;
}
lineResponse返回與該問題無關。 是什么導致修整? 如果您需要更詳盡的示例,我可以提供一個示例。
char *currentLine = "";
//Loop through the lines
while(fgets(currentLine,sizeof(input),input)){
這是你的問題。 您正在聲明一個char指針並為它分配一個字符串文字...然后嘗試讀取它。 您似乎也不了解fgets
的第二個論點; 它讀取的字符數少於該數目,並且以\\0
終止緩沖區。 還應注意,換行符存儲在緩沖區中,如果不希望將其刪除。
應該是:
char currentLine[1024]; /* arbitrary - needs to be big enough to hold your line */
while(fgets(currentLine,1024,input)) {
字符串文字(例如char* = "This is a string literal"
)是不可變的(只讀)。 它們是在編譯時創建的。
問題必須出在您如何閱讀線路上。 由於您評論說正在使用fgets()
進行閱讀,因此我猜測您使用的是32位計算機,並且您有一些類似以下的代碼:
char buffer[128];
if (fgets(&buffer, sizeof(&buffer), stdin))
{
lineResponse r = parseLine(buffer);
...
}
還有其他模糊的類似技術:
char *buffer;
if (fgets(buffer, sizeof(buffer), stdin))
...
這是因為您給fgets()
了錯誤的大小(和錯誤的地址),並且看到的大小總共為4,這意味着它只能存儲3個字符以及結尾的NUL '\\0'
。
正確的代碼可能是:
char buffer[128];
if (fgets(buffer, sizeof(buffer), stdin))
{
lineResponse r = parseLine(buffer);
...
}
要么:
char *buffer = malloc(2048);
// error check memory allocation!
if (fgets(buffer, 2048, stdin))
...
您的代碼顯示為:
char *currentLine = "";
//Loop through the lines
while(fgets(currentLine,sizeof(input),input)){
response = parseLine(currentLine);
確實(或多或少)對應於char *buffer;
我假設的版本。 您有一個額外的調整,可以在聲明FILE *input;
地方使用sizeof(input)
FILE *input;
。 如果將currentLine
保留為char *
,則需要調整第二個建議的替代方法,或者(由於沒有動態分配的內存來泄漏,因此更簡單),請使用:
char currentLine[2048];
//Loop through the lines
while (fgets(currentLine, sizeof(currentLine), input))
{
response = parseLine(currentLine);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.