简体   繁体   English

将.txt文件加载到程序中时,如何删除这些随机整数(我根本没有输入)

[英]How do i remove these random integers(which is I did not input at all) when I load a .txt file into my program

I am currently doing an assignment in C++ in which I have to load a bunch of data from a .txt file into a linked list: 我目前正在用C ++进行分配,其中必须将.txt文件中的一堆数据加载到链接列表中:

图片

Here is my load code: 这是我的加载代码:

void record::load( string fileName ) throw( recordException )
{
    ifstream inFile( fileName.c_str() );
    string c;
    string t;
    double p;
    int q;
    node *tail;

    while (!isEmpty())
    {
        remove( 1 );
    }
    size = 0;

    if ( getline(inFile, c) ||getline(inFile,t)||inFile >> p>> q) // Is file empty?
    {  // File not empty:
        try
        {
            head = new node;
            // Add the first integer to the list.
            head->cat = c;
            head->title = t;
            head->price = p;
            head->qty = q;
            head->next = NULL;
            tail = head;
            size = size + 1;
            inFile.skipws;

            // Add remaining items to linked list.
            while ( getline(inFile, c)||getline(inFile ,t)||inFile >> p>> q)
            // while(inFile.getline(c,50)||inFile.getline(t,50)||inFile>>p>>q)
            {
                tail->next = new node;
                tail = tail->next;
                tail->cat = c;
                tail->title = t;
                tail->price = p;
                tail->qty = q;
                tail->next = NULL;
                size = size + 1;
                inFile.skipws;
            }  // end while
        }  // end try
        catch (bad_alloc e)
        {
            throw recordException(
                "recordException: restore cannot allocate memory.");
        }  // end catch
    }  // end if

    inFile.close();
}

It works great, except for one issue: I get really weird numbers when I try to display the data that is loaded in my linked list. 效果很好,除了一个问题:当我尝试显示链接列表中加载的数据时,我得到了非常奇怪的数字。

This is what it looks like when my program runs: 这是我的程序运行时的样子:

图片

Can anyone help me? 谁能帮我? What can I do to remove those numbers? 如何删除这些号码? Why do these numbers occur anyway? 为什么这些数字仍然出现?

I am using C++ Codeblocks 16.01, if that is of any help. 我正在使用C ++ Codeblocks 16.01,如果有帮助的话。

Next time, don't use images, always copy/paste the actual text into your post instead. 下次,不要使用图片,而应始终将实际文本复制/粘贴到您的帖子中。

Your reading code does not match the format of your input data. 您的阅读代码与输入数据的格式不匹配。 When you call getline() , it reads until it encounters a line break or EOF. 当您调用getline() ,它将读取直到遇到换行符或EOF为止。

So, the first call to getline(inFile, c) reads the ENTIRE first line in one go: 因此,对getline(inFile, c)的第一次调用getline(inFile, c)读取了整个第一行:

"     DVD     Snow White          20     20"

Then getline(inFile,t) reads the NEXT line in one go: 然后getline(inFile,t)读取NEXT行:

"     VCD     Cinderella          10     10"

Then inFile >> p >> q tries to parse the NEXT line and fails: 然后inFile >> p >> q尝试解析NEXT行并失败:

"     MT      Wonderworld         20     30"

Since MT is not a double and Wonderworld is not an int . 由于MT不是doubleWonderworld不是int

You need to read the file line-by-line, parsing each line individually, for example: 您需要逐行读取文件,分别解析每一行,例如:

#include <string>
#include <sstream>

void record::load( std::string fileName ) throw( recordException )
{
    while (!isEmpty())
        remove( 1 );
    size = 0;

    std::ifstream inFile( fileName.c_str() );
    if (!inFile.is_open())
        return;

    std::string line;
    std::string c;
    char t[25+1] = {0}; // <-- use whatever your max title length actually is...
    double p;
    int q;
    node *newNode;

    while (std::getline(inFile, line)) // Is file empty?
    {
        std::istringstream iss(line);

        if ((iss >> c) && iss.get(t, sizeof(t)) && (iss >> p >> qty))
        {
            try
            {
                newNode = new node;
                newNode->cat = c;
                newNode->title = t;
                newNode->price = p;
                newNode->qty = q;
                newNode->next = NULL;

                if (!head)
                    head = newNode;

                if (tail)
                    tail->next = newNode;
                tail = newNode;
                ++size;
            }
            catch (const bad_alloc &e)
            {
                throw recordException(
                    "recordException: restore cannot allocate memory.");
            }
        }
    }
}

Regular Expression is much more suitable for task like this. 正则表达式更适合这样的任务。 You can use something like: 您可以使用类似:

std::string test = "      DVD      Snow White       20    20";
std::regex re("\\s*(\\S+)\\s+(\\S.*\\S)\\s+(\\d+)\\s+(\\d+)");
std::smatch match;
if (std::regex_match(test, match, re)) {
        for (size_t i = 0; i < match.size(); ++i) {
            std::cout << "submatch " << i << ": \"" << match[i] << "\"\n";
        }   
 } 

live example 现场例子

So you could read file line by line and split it using that RE: 因此,您可以逐行读取文件并使用该RE拆分文件:

std::regex re("\\s*(\\S+)\\s+(\\S.*\\S)\\s+(\\d+)\\s+(\\d+)");
std::string line;
while( std::getline( inFile, line ) ) {
    std::smatch match;
    if (!std::regex_match(test, match, re)) continue;
    std::string cat = match[1].str();
    std::string title = match[2].str();
    double price = std::stod( match[3].str() );
    int qty = std::stoi( match[4].str() );
    // you insert your node into list here 
}

Note: I made RE pattern based on your input - price contains only digits, no dot. 注意:我根据您的输入制作了RE模式-价格仅包含数字,没有点。 If it is not the case you would need to modify RE accordingly. 如果不是这种情况,则需要相应地修改RE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使我的程序在向 txt 文件中添加新条目时不会循环 - How do I make it so my program doesn't loop when adding new entries to a txt file 如何解析一个txt文件,该文件会删除除我需要的所有行之外的所有行? - How do I parse a txt file which erases all the lines except what I need? 如何使程序识别.txt文件中的不同变量类型并对其进行排序? - How do I get my program to recognize and sort the different variable types from a .txt file? 我正确地执行了这个程序吗? - Did I do this program correctly? 如何忽略额外的输入整数 - How do I ignore extra input integers 我的程序没有错误就停止了,我做错了什么? - My program stops with no errror, what did I do wrong? 当我同时拥有整数和字符数组时,如何使用 C++ 从 .txt 文件中访问数据作为链接列表的一部分? - Using C++ how do I access data from a .txt file as part of a linked list when I have both integers and character arrays? 我无法将输入文件(input.txt)中的字符串作为输入提供给 vscode 中的 C++ 程序 - I couldn't give string as input from my input file(input.txt) to c++ program in vscode 如何让我的程序等待键盘输入? - How do I get my program to wait for keyboard input? 如果输入错误,我的程序如何停止复制 - How do I my Program to stop Replicating if wrong input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM