我正在用C编写一个程序,逐行(-L)和逐字(-W)反转文本。逐行功能工作正常,但是当我使用逐字逐句的代码时,我在所有新行的开头都得到空格,奇怪的部分是空格取代字符串或字符。
我原本认为这是一个缓冲问题,但冲洗似乎没有任何影响。
应输出:
line3
line2
line1
输出:
line3
ine2
ine1
应输出:
789 456 123 line3
789 456 123 line2
789 456 123 line1
输出:
789 456 123 line3
456 123 line2
456 123 line1
这是我的代码:
char * getLine(char * line, int * sizeString){
char in;
char * temp;
int i = 0;
while((in = getchar()) != '\n' && in != EOF){
if(i > *sizeString){
temp = line;
*sizeString *=10;
line = (char *)malloc(*sizeString * sizeof(char));
strncpy(line,temp,*sizeString);
free(temp);
}
line[i++] = in;
}
line[i] = '\0';
return line;
}
void reverseWords(char * line)
{
char * token;
const char s[1] = " ";
char * wordArray[25] = {NULL};
int wordCount = 0;
//pulling the first substring out
token= strtok(line, " ");
/* walk through other tokens */
while( token != NULL )
{
//printf( "%s ", token );
wordArray[wordCount]=token;
token = strtok(NULL, s);
wordCount++;
}
//printf("\n");
wordCount--;
while(wordCount>=0)
{
printf("%s ", wordArray[wordCount]);
wordCount--;
}
printf("\n");
}
int main(int argc, const char * argv[])
{
int sizeString = 10;
char * lines[1024] = {NULL};
char ** linePtr;
linePtr = lines;
if (!strcmp(argv[1],"-W"))
{
while(!feof(stdin))
{
*linePtr = (char *)malloc(sizeString * sizeof(char));
*linePtr = getLine( *linePtr, &sizeString);
*linePtr++;
}
linePtr--;
while(linePtr>=lines)
{
reverseWords(*linePtr);
//printf("%s\n",*linePtr);
linePtr--;
}
return 0;
}
if (!strcmp(argv[1],"-L"))
{
while(!feof(stdin))
{
*linePtr = (char *)malloc(sizeString * sizeof(char));
*linePtr = getLine( *linePtr, &sizeString);
*linePtr++;
}
linePtr--;
while(linePtr>=lines)
{
printf("%s\n",*linePtr);
linePtr--;
}
return 0;
}
}