[英]read a string from the file till we get '\n' character or EOF in c/c++
[英]read data from file till end of line in C/C++
閱讀直到文件末尾是常見的,但我感興趣的是如何從文本文件中讀取數據(一系列數字)直到行尾 ? 我的任務是從文件中讀取幾個數字系列,這些數字位於新行中。 以下是輸入示例:
1 2 53 7 27 8
67 5 2
1 56 9 100 2 3 13 101 78
第一系列:1 2 53 7 27 8
第二個:67 5 2
第三名:1 56 9 100 2 3 13 101 78
我必須分別從文件中讀取它們,但每個都要直到行尾。 我有這個代碼:
#include <stdio.h>
FILE *fp;
const char EOL = '\\0';
void main()
{
fp = fopen("26.txt", "r");
char buffer[128];
int a[100];
int i = 0;
freopen("26.txt","r",stdin);
while(scanf("%d",&a[i])==1 && buffer[i] != EOL)
i++;
int n = i;
fclose(stdin);
}
它會一直讀到文件的末尾,因此它沒有達到我預期的效果。 你有什么建議?
使用fgets()讀取整行,然后解析該行(可能使用strtol() )。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char buffer[10000];
char *pbuff;
int value;
while (1) {
if (!fgets(buffer, sizeof buffer, stdin)) break;
printf("Line contains");
pbuff = buffer;
while (1) {
if (*pbuff == '\n') break;
value = strtol(pbuff, &pbuff, 10);
printf(" %d", value);
}
printf("\n");
}
return 0;
}
\\ n應該是新行的轉義,試試這個
const char EOL = '\n';
你搞定了嗎? 這應該有所幫助:
#include <stdio.h>
FILE *fp;
const char EOL = '\n'; // unused . . .
void main()
{
fp = fopen("26.txt", "r");
char buffer[128];
int a[100];
int i = 0;
freopen("26.txt","r",stdin);
while(scanf("%i",&a[i])==1 && buffer[i] != EOF)
++i;
//print values parsed to int array.
for(int j=0; j<i; ++j)
printf("[%i]: %i\n",j,a[j]);
fclose(stdin);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.