如何逐行读取文件并获取特定的字符或整数? [英] How to read file line by line and get specific chars or ints?
本文介绍了如何逐行读取文件并获取特定的字符或整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下输入文件:
3(3,3)
1(5,4)
2(7,7)
V
H
我有以下代码可以打印其中的所有内容:
And I have the following code to print everything in it:
char const * const fileName = argv[1]; /* should check that argc > 1 */
FILE *file = fopen(fileName, "r"); /* should check the result */
char line[256];
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
但是我只想从每一行而不是括号中检索char
或int
.我该怎么写呢?
But I want to only retrieve the char
or the int
from each line and not the brackets. How can I write something to do that?
推荐答案
您只想检查每个字符和数字,只接受字符和数字:
You just want to check on every character and number and accept only the chars and number:
const char *fileName = "C:\\file.txt";
FILE *file = fopen(fileName, "r");
int c = 0;
while ((c = fgetc(file)) != EOF) {
if (isdigit(c) || isalpha(c) || c == '\n')
printf("%c", c);
}
fclose(file);
结果:
这篇关于如何逐行读取文件并获取特定的字符或整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文