在每行中读取文件中的给定数字 [英] Reading given numbers in file in each line
本文介绍了在每行中读取文件中的给定数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们假设我们有文件,
6
3
4
8
1
9
13
告诉我如何从文件中读取并存储这些数组中的数字。
//首先尝试
lets suppose in file we have,
6
3
4
8
1
9
13
Tell me how to read it from file and store these numbers in an array.
//First try
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<fstream>
using namespace std;
char keys[25];
int main()
{
int count=0;
string data;
char k[20];
ifstream my("keys.txt");
//if (myfile.is_open())
//{
while (! my.eof() )
{
getline(my,data);
k[count]=data;
cout << data << endl;
count++;
}
my.close();
//size=data.length();
//cout<<"Length of string is : "<<size<<endl;
cout<<"The number of keys are :"<<count<<endl;
for(int i=0;i<count;i++)>
{
k[i]=data[i];
cout<<k[i];
}
/*for(int j=0;j!='\0';j++)
{
k[j]=data[j];
}
for(int i=0;i!='\0';i++)
{
cout<<k[i];
cout<<endl;
}
//}
//else cout << "Unable to open file";
for(int j=0;j<size;j++)>
{
keys[j]=data[j];
}
*/
system("pause");
return 0;
}
////////////////// ///////////////////////////////
Second Prog
/////////////////////////////////////////////////
Second Prog
#include<iostream>
//#include<stdio.h>
//#include<stdlib.h>
#include<conio.h>
using namespace std;
int main()
{
FILE *k;
int v;
k=fopen("pre1.c","r");
while(v=getc( k )!=EOF)
{
putch(v);
cout<<"Value is :"<<v<<endl;
}
fclose(k);
system("pause");
return 0;
}
推荐答案
- 从文件中读取下一行。
- 解析该行以查看它是否是有效的数字字符串,如果没有则显示消息。
- 将字符串转换为整数。
- 存储数组的整数
- 重复直到不再有数据
#include<stdio.h>
int main()
{
freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int c,i=0;
int array[100];
while((scanf("%d",&c))!=EOF)
{
array[i++]=c;
}
//getchar();
return 0;
}
Google [ ^ ]
首次搜索结果:输入/输出文件 [< a href =http ://www.cplusplus.com/doc/tutorial/files/\"target =_ blanktitle =新窗口> ^ ]
Google[^]
First search result: Input/Output with files[^]
std::string myString = "99";
int value = atoi(myString.c_str());
最好的问候
Espen Harlinn
Best regards
Espen Harlinn
这篇关于在每行中读取文件中的给定数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文