[英]C Reading in integers from txt without fscanf
I'm trying to take getbits from K&R C 2.9 and pass a text file containing ints through, check to make sure getbits() can handle them, and format the ouput to another txt file. 我正在尝试从K&R C 2.9中获取getbits,并通过一个包含int的文本文件,检查以确保getbits()可以处理它们,并将输出格式化为另一个txt文件。 I'm stumped and my instructor told me NOT to use fscanf, use stdin and maybe scanf.
我很沮丧,我的教练告诉我不要使用fscanf,不要使用stdin,也不要使用scanf。
Here's my code 这是我的代码
include <stdio.h>
unsigned int getbits(unsigned int x, int p, int n)
{
return (x >> (p + 1 - n)) & ~(~0 << n);
}
int main()
{
File * ipf = fopen("input.txt", "r");
int x = 0 , p = 0, n = 0, b = 0;
while(fscanf(ipf, "%d, %d, %u", &p, &n, &x) != EOF)
{
if(x < 4294967296 && p < 32 && n < p + 2)
{
b = getbits(x,p,n);
printf("gebits( x = %u, p = %d, n = %d) = %u\n", x, p, n, b);
}
else { printf("ERROR"); }
}
return 0;
}
input.txt input.txt中
2,1,127
2,4,127
31,3,1431655765
32,3,1431655765
output.txt output.txt的
getbits(x=127, p=2, n=1) = 1
ERROR
getbits(x=1431655765, p=31, n=3) = 2
ERROR
I know this is all basic but I really apreciate any help :) 我知道这是基本知识,但我非常感谢您的帮助:)
You can also read an integer from the file without using fscanf
. 您也可以不使用
fscanf
从文件读取整数。 Here is some code which reads content from the file, without using fscanf
. 这是一些代码,无需使用
fscanf
即可从文件读取内容。 I also corrected some data type declaration for your value in which you compared int
data to long long
. 我还为您的值更正了一些数据类型声明,在其中将
int
数据与long long
。
int main()
{
FILE * ipf = fopen("input.txt", "r");
long long x = 0 , p = 0, n = 0, b = 0;
char * line = NULL;
size_t len = 0;
ssize_t read;
char *token;
while ((read = getline(&line, &len, ipf)) != -1)
{
token=strtok(line,",");
p=atoi(token);
token=strtok(NULL,",");
n=atoi(token);
token=strtok(NULL,"");
x=atoi(token);
if(x < 4294967296 && p < 32 && n < p + 2)
{
b = getbits(x,p,n);
printf("gebits( x = %lld, p = %lld, n = %lld) = %lld\n", x, p, n, b);
}
else { printf("ERROR\n"); }
}
return 0;
}
For Windows, use the following solution: 对于Windows,请使用以下解决方案:
int main()
{
FILE * ipf = fopen("input.txt", "r");
long long x = 0 , p = 0, n = 0, b = 0;
char line [256];
size_t len = 0;
ssize_t read;
char *token;
while ((fgets(line,256, ipf)) != 0)
{
token=strtok(line,",");
p=atoi(token);
token=strtok(NULL,",");
n=atoi(token);
token=strtok(NULL,"");
x=atoi(token);
if(x < 4294967296 && p < 32 && n < p + 2)
{
b = getbits(x,p,n);
printf("gebits( x = %lld, p = %lld, n = %lld) = %lld\n", x, p, n, b);
}
else { printf("ERROR\n"); }
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.