从文本文件中读取并通过定界符分开
Read from text file and seperate by a delimiter
我正在尝试从文本文件中阅读,然后尝试将它们放在对象中。
,但我不确定如何将一条线分开为两个变量(作为定界符的空间(。
文本文件格式如下(前2个条目(:
Text1 [txt1]
This is a description of text 1.More description of Text 1 here blah blah blah.
Text2 [txt2]
This is the description of text 2.
我想将它们分为三个sperate变量,一个用于名称(text1(,类型是方括号([txt1(,最后是描述(这是文本1的描述。(
我到目前为止的代码不会分开text1和[txt1]:
if (myfile.is_open()) {
string buffer;
string currentText= "empty";
string currentType= "empty";
string currentDescription = "empty";
while (!myfile.eof()) {
getline(myfile, buffer); // Would like to seprate this line into two variables
currentText = buffer;
if (buffer == "") continue;
getline(myfile, buffer);
currentDescription = buffer;
if (buffer == "") continue;
TextObj newtext(currentText, iWantToEnterTypeHere, currentDescription);
this->textVector.push_back(newText);
}
myfile.close();
我希望这很有意义,我将感谢任何帮助。欢呼
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
int main() {
fstream myfile;
myfile.open ("example.txt");
if (myfile.is_open()) {
string line;
while (getline (myfile,line)) {
vector<string> tokens;
const string s = line;
char delim =' ';
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
tokens.push_back(item);
}
getline (myfile,line);
tokens.push_back(line);
//Here you can create object using token[0], token[1], token[2] and can remove cout statements
for(int i = 0; i < tokens.size(); i++) {
cout << tokens[i] << endl;
}
cout<<"=================n";
}
}
myfile.close();
return 1;
}
我希望这会有所帮助。您可以根据注释块中指定的对象创建对象,并删除COUT语句。添加了它们只是为了添加澄清。
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何根据单词在文本中出现的概率输出单词
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- C++试图读取一个文件并输出到另一个文本文件
- 从文本文件中读取并通过定界符分开