我被困在一个硬件任务上,我需要编写一个程序,将一堆英文单词(在输入 .txt 文件中由换行符分隔的列表中)转换为一堆 Pig 拉丁文单词(到一个列表中由输出 .txt 文件中的新行分隔)。我已经非常接近了,但是strncat
我正在使用的函数(字符串连接)函数以某种方式抛出了一个新行,这真的抛出了我正在打印的文本stdout
(现在用它来测试)。任何想法为什么会发生这种情况?这是我的代码:
#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;
}