>我被困在一个硬件作业上,我需要编写一个程序,将一堆英语单词(在输入.txt文件中由新行分隔的列表中(转换为一堆 Pig Latin 单词(转换为输出.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] = ' '; //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] = {' '};
char cStr[MAX_STR_SIZE] = {' '};
char dStr[] = {'-',' '};
char ayStr[] = {'a','y',' '};
char wayStr[] = {'w','a','y',' '};
pStrPtr = pStr;
while (*strPtr != ' ')
{
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;
}
这段代码中有很多奇怪之处,但是您询问的问题是由convertToPigLatin
中的while循环创建的。你在*strPtr != ' '
时循环,n
肯定不是