c++关于文件读取的问题
我目录下有个a.txt文件里面内容类似这样的
百事可乐 2元
香烟 5元
......
然后我想在c++程序里面读取这些内容,并把里面的信息以链表形式存放到这个结构体中
typedef struct
{
string goods; //存放商品名
int price; //存放价格
}test;
请问大牛们,这该如何实现呢?
[解决办法]
会读文件,会链表,就会写程序了!
练练吧,太简单了!
看看基础书籍,马上就会了,相信自己的能力!
[解决办法]
另外给你个建议,结构体中最好用基础数据类型,如将你这里的string改为:char goods[20];
[解决办法]
a.cpp
- C/C++ code
#include <stdio.h>#include <string>using namespace std;typedef struct tagNode{ char goods[20]; int price;}Node;int main(){ Node node; char line[100] = {0}; FILE *fp = fopen("a.txt", "r"); while(fgets(line, 100, fp) != NULL) // 从文件读取一行数据 { //printf("line = [%s]\n", line); sscanf(line, "%s %d", node.goods, &node.price); // 从line中提取数据到node printf("node.goods = %s, node.price = %d\n", node.goods, node.price); } fclose(fp); return 0;}
[解决办法]
- C/C++ code
#include <fstream>#include <iostream>#include <string>using namespace std;struct test{string goods;int price;test *next;};int main(){ifstream infile;infile.open("a.txt",ifstream::in);if(!infile.is_open()){cout << "Unable to open the file:a.txt"<<endl; throw;}string s;test *head = new test;test *p,*q = head;string words;while(getline(s,infile)){ istringstream sstream(s); p = new test; sstream >> p->goods; sstream >> p->price; q->next = p; q = p;}infile.close();q->next = NULL;q = head->next;while(q){cout << q->goods << " " << q->price << endl; q=q->next;}while(head){ q = head->next; delete head; head = q;}return 0;}
[解决办法]
在加上个#include <sstream>
[解决办法]
[解决办法]
[解决办法]
自己查一下