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

C++ Adding strings to list to a txt file by command line app

本文关键字:字符串 添加 文件 txt 命令行 应用 C++      更新时间:2023-10-16

好吧,伙计们,很抱歉这个愚蠢的问题,但我',开始编程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;
                };
            };

但问题是,我不知道如何将其"合并"为一个可以正常工作的

有什么帮助吗?

假设用户将每一行都写为"名称数量",那么以下代码应该可以完成这项工作:

#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()中进行更改。