更多参考其他文档菜鸟文档、W3C、微软C++文档
参考资料:
- C++中string转int
- C++ getline函数用法详解
- C++文件读写详解(ofstream,ifstream,fstream)
- C++系列:标准模板库STL(1)(七)
#include<iostream> #include<string> #include <sstream> #include<fstream> using namespace std;
typedef struct book{ string ISBN; string name; int yuan; }book;
int main() { stringstream stream; string x; book newbook[5]; ifstream srcFile("book.txt", ios::in); 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); newbook[i].name.assign(x,18,12); mid.assign(x,31,3); stream << mid; stream >> newbook[i].yuan ; 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); 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; }
|
如果有任何疑问欢迎留言。