从冒号分隔.txt文件中提取信息,C++

Extract Information from colon seperated .txt file, C++

本文关键字:提取 信息 C++ 文件 分隔 txt      更新时间:2023-10-16

伙计们。我正在编写这个小测试程序,将文本文件从"EXAMPLE.txt"读取到我的主程序中。在输出时,我输入"*"以显示输出期间的数据是我要提取的数据并定位到数组中。假设在这个测试程序中,我想提取的数据是">JY9757AC",">AZ9107AC",">GY9Z970C"。 但是在那之后,我做了一个尝试运行,在输出方面我遇到了这个问题。

示例

.txt
ABC:JY9757AC
HDMI:AZ9107AC
SNOC:GY9Z970C

主要。.CPP

main()
{
    string output;
    ifstream readExample;
    readExample.open("EXAMPLE.txt");  
    while(readExample.eof())
    {
        getline(readExample,output,':');
        cout << "* " << output <<endl; 
    }
}

输出

* ABC       //while loop output the "ABC", which is the data that I don't want.
* JY9757AC
HDMI        //it work's well, as what I expected and so and the SNOC below
* AZ9107AC
SNOC
* GY9Z970C

我不知道为什么输出上显示">* ABC">,我的逻辑有什么问题吗? 或者我在 while 循环中错过了一些东西?提前感谢您帮助解决我的代码!

getlinedelim 参数替换新行的默认分隔符""。您目前得到的"行"是:

ABC
JY9757ACnHDMI
AZ9107ACnSNOC
GY9Z970C

你可以做的是更多这样的事情(如果你的输出像GY9Z970C(是固定大小的:

ssize_t len = getline(readExample,output,':');
cout << "* " << (char*)(output + (len - 8)) <<endl; 

输出存储示例的第一个提取.txt并打印它,后跟 *。在第一次迭代中output = "ABC";在第二次迭代中output = "JY9757AC"; 。我在 while 循环中添加了一个getline(),用于读取行中不需要的部分。我还添加了一个string[]来存储提取的值。

#include <fstream>
#include <string>

using namespace std;
int main()
{
    string output, notWanted, stringArray[3];
    int i = 0;
    ifstream readExample;
    readExample.open("EXAMPLE.txt");
    while (!readExample.eof())
    {
        getline(readExample, notWanted, ':');
        getline(readExample, output);
        cout << "* " << output << endl;
        stringArray[i++] = output;
    }
    cin.get();
    return 0;
}

首先,我假设while循环是while(!readExample.eof()),否则根本不应该有输出。

其次,对于你的问题,第一个getline(readExample,output,':');output中读"ABC",所以在下一行它输出* ABC,这正是你得到的。不足为奇。