我被困在硬件分配中,在那裏我需要編寫一個程序,將一堆英文單詞(在輸入.txt文件中以換行符分隔的列表中)轉換爲一羣豬拉丁文字(在輸出.txt文件中以換行符分隔)。我已經非常接近了,但我使用的strncat
函數(字符串concatentation)函數以某種方式拋出一個新行,這真的拋出了我正在打印的文本到stdout
(使用它來測試現在)。任何想法,爲什麼這可能會發生?這裏是我的代碼:C中的字符串處理問題
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_SIZE 100
char * convertToPigLatin (char * strPtr, char * pLatinStr);
int main(int argc, char *argv[])
{
char str[MAX_STR_SIZE];
char pStr[MAX_STR_SIZE];
//char *pStrPtr;
FILE *fileInPtr; //Create file name
FILE *fileOutPtr;
fileInPtr = fopen("pigLatinIn.txt", "r"); //Assign text to file
fileOutPtr = fopen("pigLatinOut.txt", "w");
//pStrPtr = pStr;
if(fileInPtr == NULL) //Check if file exists
{
printf("Failed");
exit(-1);
}
do //Cycles until end of text
{
fgets(str, 29, fileInPtr); //Assigns word to *char
str[29] = '\0'; //Optional: Whole line
convertToPigLatin(str, pStr);
fprintf(fileOutPtr, "%s", pStr);
} while(!feof(fileInPtr));
system("pause");
}
char * convertToPigLatin (const char * strPtr, char * pStrPtr)
{
int VowelDetect = 0;
int LoopCounter = 0;
int consonantCounter = 0;
char pStr[MAX_STR_SIZE] = {'\0'};
char cStr[MAX_STR_SIZE] = {'\0'};
char dStr[] = {'-','\0'};
char ayStr[] = {'a','y','\0'};
char wayStr[] = {'w','a','y','\0'};
pStrPtr = pStr;
while (*strPtr != '\0')
{
if (*strPtr == 'a' || *strPtr == 'e' || *strPtr == 'i' || *strPtr == 'o' || *strPtr == 'u' || VowelDetect ==1)
{
strncat(pStr, strPtr, 1);
VowelDetect = 1;
}
else
{
strncat(cStr, strPtr, 1);
consonantCounter++;
}
*strPtr++;
}
strcat(pStr, dStr);
if (consonantCounter == 0)
{
strcat(pStr, wayStr);
}
else
{
strcat(pStr, cStr);
strcat(pStr, ayStr);
}
printf("%s", pStr);
// return pStrPtr;
}
你想快速,痛苦還是緩慢無痛? – chris
我的猜測*是你至少有一行的字符數小於你用'fgets()'讀的'29'的字符數,因此你的循環中只有一個嵌入的CR或LF, strcat's到你的字符串,因爲你不排除任何這些字符。是什麼讓你決定一次任意讀取29個字符,並假定它是一行? –
是的,我不認爲'strncat()'增加了一個換行符,只是'fgets()'正在讀取已經在輸入文件中的文件。在通過'convertToPigLatin()'運行之前,您應該將其去掉。 –