[英]I want to read and add integers from a file line by line in C. File also has alphabets and special characters
[英]Read integers AND characters from file line by line in C
我有一个这种形式的 txt 文件:
11
10
BU
1U
0U
0U
...
我想从 C 的文件中一个一个地读取每个数字/字符。 前两行包含 2 个整数,行的 rest 首先包含一个字母/整数,然后是一个字母。 不幸的是,我不知道如何实现这一点,因为您不知道您阅读的是 integer 还是字符。
有人可以帮我解决这个问题吗?
这是一个关于如何处理文件中的每个字符并在满足时转换为 integer 的最小示例。 我相信您可以尝试根据您的需要调整此代码。 该代码还跳转换行符和 EOF。
为了更好地理解这是如何工作的,请查看标准ASCII 。
#include<stdio.h>
int main(){
FILE * handle;
handle = fopen("data.txt","r");
char var;
while(var!=EOF){
var=fgetc(handle);
if(var>47&&var<58){
printf("Value: %d",var);
printf(" Integer: %d \n",var-48);
}
else if(var!=10 && var!=-1){
printf("Value: %d",var);
printf(" Char or other: %c\n",var);
}
}
}
Output:
Value: 49 Integer: 1
Value: 49 Integer: 1
Value: 49 Integer: 1
Value: 48 Integer: 0
Value: 66 Char or other: B
Value: 85 Char or other: U
Value: 49 Integer: 1
Value: 85 Char or other: U
Value: 48 Integer: 0
Value: 85 Char or other: U
Value: 48 Integer: 0
Value: 85 Char or other: U
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.