我被困在一项 HW 作业中,我需要编写一个程序,将一堆英语单词(在输入 .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] = '\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;
}
最佳答案
这段代码中有很多奇怪的地方,但您所问的问题是由 convertToPigLatin
中的 while 循环造成的。当 *strPtr != '\0'
循环时,\n
肯定不是 \0
,因此您将其添加到 pStr
.
现在剩下的代码,只是一些注释:
- 使用
strncat
复制一个字符是一种奇怪的用法。通常,人们会改用简单的字符分配(如str1[i] = str2[j]
) *strPtr++
正在递增指针并取消引用它,但随后对取消引用的值不执行任何操作。你只需要strPtr++
就可以了。- 您可以使用
char str[] = "some string"
创建字符串文字。您不需要使用数组初始化语法。
那些是我没有详细阅读就跳出来的。祝你 future 的任务顺利。
编辑补充说,在这些情况下,使用调试器单步执行代码非常有值(value)。您会确切地看到添加换行符的位置。
关于c - C 中字符串处理的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17847090/