[英]Reading only first character of each line in file
我目前正在尝试读取和处理“ .c”文件每一行中的第一个字符。 到目前为止,我已经看过这段代码了,但是n甚至没有在循环中打印出来:
void FileProcess(char* FilePath)
{
char mystring [100];
FILE* pFile;
int upper = 0;
int lower = 0;
char c;
int n =0;
pFile = fopen (FilePath , "r");
do {
c = fgetc (pFile);
if (isupper(c)) n++;
} while (c != EOF);
printf("6");
printf(n);
fclose (pFile);
}
几点:
printf
。 令人惊讶的是您摆脱了它-这通常会造成破坏。 fgets
将整行读入缓冲区(确保缓冲区足够大)。 示例(使用@chux的输入进行更新-并添加了一些其他代码来帮助调试“ n = 1”问题):
void FileProcess(char* FilePath)
{
char mystring [1000];
FILE* pFile;
int upper = 0;
int lower = 0;
char c;
int n =0;
pFile = fopen (FilePath , "r");
printf("First non-space characters encountered:\n")
while(fgets( myString, 1000, pFile) != NULL)
int jj = -1;
while(++jj < strlen(myString)) {
if ((c = myString[jj]) != ' ') break;
}
printf("%c", c);
if (isupper(c)) {
printf("*U*\n"); // print *U* to show character recognized as uppercase
n++;
}
else {
printf("*L*\n"); // print *L* to show character was recognized as not uppercase
}
}
printf("\n");
printf("n is %d\n", n);
fclose (pFile);
}
注意,还有其他更强大的读取行方法可以确保您拥有所有内容(我最喜欢的是getline()
但并非所有编译器都可用)。 如果您确定您的代码行不是很长,这将起作用(不过,使缓冲区略大于100个字符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.