C语言中从文件中读取数值读到回车停止

input.txt文件中有
2 3 4 5 6
7
我想让它读到6停止,怎么写代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{ char buffer[256],*p;
FILE *fp;
int a[20],n,i;
if ( fp=fopen("file.txt","r") )
{ fgets(buffer+1,256,fp); fclose(fp); //读1行
n=0; p=buffer; buffer[0]='0';
while ( *p )
{ p++; a[n]=atoi(p); n++; //转换当前数据
while ( *p!=' ' ) { p++; if ( *p==0 ) break; } //找空格,以便转换空格后面的数据
}
for ( i=0;i<n;i++ ) printf("%d ",a[i]);
printf("\n");
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-11-24
fgets函数循环接收单个字符,接收后判断若等于“\n”就停止。
例如
char *p = (char *)malloc(sizeof(char));
fgets(p,sizeof(char),文件标识符);
if(*p == '\n')
...
free(p);
第2个回答  2013-11-25
char temp = 0;
int num[100] = {0};
int i = 0;
FILE *fp = fopen("input.txt",r);
i = 0;
while(1)
{
fscanf(fp,"%c",&temp);

if(temp == '\n')

{

break;

}

if(temp != ' ')

{

num[i++] = temp;

}

}
相似回答