C++以文本形式按行读取文件数据
参考资料:
//目的:以文本形式将数据按行读入到定义好的数据对象中
#include
#include
#include
#include
using namespace std;
//以图书的数据为例
typedef struct book{
string ISBN;
string name;
int yuan;
}book;
int main()
{
stringstream stream; //定义stringstream这个对象
string x;
book newbook[5];
ifstream srcFile("book.txt", ios::in); //以文本模式打开in.txt备读
if (!srcFile) { //打开失败
cout << "error opening source file." << endl;
return 0;
}
int i= 0;
string mid;
while (getline(srcFile,x)) {
newbook\[i\].ISBN.assign(x,0,17); //按位复制 从第1个字符开始复制17个字符,注意中文占两个字符。
newbook\[i\].name.assign(x,18,12);
mid.assign(x,31,3);
stream << mid; //数据输入string转换为int
stream >> newbook\[i\].yuan ; //将转换为int的数据输出
stream.clear(); //重复使用需要先清空
cout << " ok " << endl;
i++;
}
for(int i= 0;i<5 ;i++)
{
cout << newbook\[i\].ISBN<< " " << newbook\[i\].name<< " " << newbook\[i\].yuan<< " ok " << endl;
}
srcFile.close(); //关闭文件
return 0;
}
然而可以不用这麻烦,这种定位复制的方法会将空格也复制,所以如果是对齐的数据的话,因为数据长度不相同导致复制了很多长度不相同的空格,还要想办法去除,实际上是很麻烦的。
好了,本来应该很简单就搞定的,这样:
int main()
{
book newbook[5];
ifstream srcFile("book.txt", ios::in); //以文本模式打开in.txt备读
if (!srcFile) { //打开失败
cout << "error opening source file." << endl;
return 0;
}
int i= 0;
while(!srcFile.eof()) //判断文件是否读到最后
{
srcFile>>L.elem\[i\].isbn>>L.elem\[i\].bookname>>L.elem\[i\].price; //按类型读,遇空格结束一个数据,而且类型是匹配的
L.length++;
i++;
}
for(int i= 0;i<5 ;i++)
{
cout << newbook\[i\].ISBN<< " " << newbook\[i\].name<< " " << newbook\[i\].yuan<< " ok " << endl;
}
srcFile.close(); //关闭文件
return 0;
}
如果有任何疑问欢迎留言。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Q's blog!
