好的,很抱歉提出这些愚蠢的问题,但是我开始使用 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;
};
};
但问题是,我不知道如何将它“合并”成一个可以工作的
有什么帮助吗?
最佳答案
假设用户将每一行写为“name quantity”,那么下面的代码应该可以完成这项工作:
#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()
中更改它。
关于C++通过命令行应用程序将要列表的字符串添加到txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181871/