C++ 通过命令行应用将要列出的字符串添加到 txt 文件
C++ Adding strings to list to a txt file by command line app
好吧,伙计们,很抱歉这个愚蠢的问题,但我',开始编程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()
中进行更改。
相关文章:
- 如何将字符串添加到布谷鸟过滤器?
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 如何在C++中为字符串添加字符?
- 在特定位置为字符串添加空格
- 有没有办法将字符串添加到 Vector 中,但前提是它尚不存在?->C++
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- 如何使用函数将字符串添加到向量中
- 如何在 c++ 中将字符串添加到动态数组?
- 向字符串添加字符
- 向字符串添加位值
- 如何从用户那里接收多个字符串并将这些字符串添加到 c++ 中的数组中?
- 字符串添加数字 C++
- std::字符串添加到字符*
- C++ 向字符串添加"u"
- JSONCPP正在向字符串添加额外的双引号
- C 将N字符串添加到字符串流中
- 以简单且更少的代码方式将字符串添加在一起
- 字符串添加或减法操作员
- 将字符串添加到2D数组并显示COUT消息(没有错误消息?)的错误
- 如何使用递归向字符串添加逗号