我正在尝试从K&R C 2.9获取getbits并传递一个包含ints的文本文件,检查以确保getbits()可以处理它们,并将输出格式化为另一个txt文件。我很困惑,我的导师告诉我不要使用 fscanf,使用 stdin,也许使用 scanf。
这是我的代码
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) = %un", x, p, n, b);
}
else { printf("ERROR"); }
}
return 0;
}
输入.txt
2,1,127
2,4,127
31,3,1431655765
32,3,1431655765
输出.txt
getbits(x=127, p=2, n=1) = 1
ERROR
getbits(x=1431655765, p=31, n=3) = 2
ERROR
我知道这都是基本的,但我真的很感激任何帮助:)
您也可以从文件中读取整数,而无需使用 fscanf
。下面是一些从文件中读取内容的代码,而无需使用 fscanf
。我还更正了您的值的一些数据类型声明,您将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) = %lldn", x, p, n, b);
}
else { printf("ERRORn"); }
}
return 0;
}
对于 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) = %lldn", x, p, n, b);
}
else { printf("ERRORn"); }
}
return 0;
}