C++通过命令行应用程序将要列表的字符串添加到txt文件

标签 c++ list fstream

好的,很抱歉提出这些愚蠢的问题,但是我开始使用 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/

相关文章:

java - 创建 ListIterator 时会发生什么?

python - 通过在 Python 中切片列表来分配值的紧凑方法

python - 如何使用python从列表中读取数据并将特定值索引到Elasticsearch中?

c++ - 替换txt文件中的行c++

c++ - 读取文件时两次获得相同的输出

c++ - C++ 中的装饰器设计模式

c++ - 关于对象的复制

c++ - 为什么 GCC 不使用 LOAD(无围栏)和 STORE+SFENCE 来实现顺序一致性?

C++如何动态加载第3方DLL文件

c++ - 如何使用 C++ 程序快速地将文件从一个位置复制到另一个位置?