好的,对不起这个愚蠢的问题,但是我在C ++开始编程
必须保存"字符串列表"到txt文件。
我知道如何打开文件
我做过类似的事情并且正在努力。
void open_file()
{
string list_cont;
fstream newlist;
newlist.open("lista.txt", ios::in);
while (newlist.good())
{
getline(newlist, list_cont);
cout << list_cont << endl;
}
newlist.close();
}
除了它,练习我的编程我做了类似的事情
struct list{
przedmiot *first;
void add_przedmiot(string name, string quantity);
void delete_przedmiot(int nr);
void show_list();
list();
};
list::list(){
first = 0;
};
void list::show_list()
{
przedmiot *temp = first;
while (temp)
{
cout << "przedmiot: " << temp->name<<endl<< "ilosc: " << temp->quantity <<endl;
temp = temp->next;
}
}
void list::add_przedmiot(string name, string quantity)
{
przedmiot *nowy = new przedmiot;
nowy->name = name;
nowy->quantity = quantity;
if (first == 0)
{
first = nowy;
}
else{
przedmiot *temp = first;
while (temp->next)
{
temp = temp->next;
}
temp->next = nowy;
nowy->next = 0;
};
};
但问题是,我不知道如何&#34;合并&#34;这将是一个将工作的
任何帮助人员?
答案 0 :(得分:2)
假设用户将每一行都写为“名称 数量”,那么以下代码应该完成这项工作:
#include <fstream>
#include <sstream>
#include <iostream>
int main(){
using namespace std;
string input, name, quantity;
list myList;
ofstream file;
file.open("lista.txt");
while( getline (cin, input) ) { //reading one line from standard input
istringstream ss(input); // converting to convenient format
getline(ss, name, ' '); //extract first field (until space)
getline(ss, quantity); // extract second field (until end of line)
myList.add_przedmiot( name, quantity);
file << name << quantity << endl; // write to file
}
file.close()
}
注意我使用了istringstream
类,它将字符串转换为流并且更容易解析。
此外,getline()
的默认分隔符为\n
,因此循环内该函数的第二个出现位置为第二个字段。
您还应该检查输入的有效性。此外,如果字段中有 空格,则应定义适当的分隔符(逗号,分号),并在第一个getline()
中更改它。