我正在开发一个 MediaPlayer 项目,该项目将播放文本文件而不是音频或视频。我的问题是如何显示 C 字符串数组中的字符串?例如,如果在文本文件中我有(不带引号):
**"This is only test"**
在我的程序中,我想一次显示一个单词,例如:
This
is
only
test
我该怎么做?这是到目前为止我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Global variables
int position=0; //to set the player position
float rate = 1.0; //the rate of playback
void LoadFile(const char *fileName, char *text){
FILE *ifp; //a file pointer for file read/write
//opening the file
ifp = fopen(fileName, "r");
if(ifp == NULL){
fprintf(stderr, "Can't open input file \"%s\"!\n",fileName);
exit(1);
}
else{
fgets(text,50,ifp); //getting the text from the file
}
//closing the file
fclose(ifp);
}
void *Start();
void *Stop();
void Rewind();
void SeekTo(int byteOffset);
void setRate(float rate);
int main(void){
int i = 0;
char choice;
char fileName[25];
char lineOfText[50]; //holds the text inside the file
printf("Please enter the file you want to open: ");
scanf("%s", fileName);
LoadFile(fileName,lineOfText);
printf("%s",lineOfText); //I will display the whole string
return 0;
}
最佳答案
使用strtok函数
#include < stdio.h >
#include < string.h >
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
//printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
这段代码将给出输出
This
a
sample
string
要进一步了解,请参阅以下内容
关于c - 将文本文件读入 c 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10856283/