【问题标题】:Reading a text file into a struct array c++将文本文件读入结构数组 C++
【发布时间】:2017-04-18 17:37:15
【问题描述】:

这是一个家庭作业,但我展示的是一个小型测试程序,用于我的大部分作业。

一开始,我将在文件“songs.txt”中有一个歌曲列表。我当前的文件是这样的。

Maneater;4;32
Whip It;2;41
Wake Me Up Before You Go-Go;3;45

该文件仅包含歌曲标题以及以分钟和秒为单位的持续时间,标题、分钟和秒以分号分隔。完整的文件也应该包含艺术家和专辑,都用分号分隔。无论如何,代码。

#include<iostream>
#include<cstring>
#include<fstream>
#include<cstdlib>
using namespace std;

const int CAP = 100;
const int MAXCHAR = 101;

struct songInfo
{
    char title[CAP];
    char durMin[CAP];
    char durSec[CAP];

};

void getData(songInfo Song[], int listSize, int charSize);

int main()
{
    string fileName;
    songInfo Song[CAP];
    ifstream inFile;

    cout << "What is the file location?: ";
    cin >> fileName;
    inFile.open(fileName.c_str());
    if (inFile.fail())
    {
        cout << "Cannot open file " << fileName << endl;
        exit(1);
    }

    getData(Song, CAP, MAXCHAR);

    for (int i=0;i<CAP;i++)
    {
        cout << Song[i].title << " - "
            << Song[i].durMin << ":"
            << Song[i].durSec << endl;
    }

    cout << "Press any button to continue..." << endl;
    cin.get(); cin.get();

return 0;
}

void getData(songInfo Song[], int listSize, int charSize)
{


    for (int i = 0; i < listSize; i++)
    {
        cin.get(Song[i].title, charSize, ';');
        cin.get(Song[i].durMin, charSize, ';');
        cin.get(Song[i].durSec, charSize, '\n');
        i++;
        cin.ignore();
    }
}

程序可以正常编译,但输出不是我想要的。应该发生什么:

  1. Test.cpp 打开songs.txt

  2. 将第一个char数组读入Song[i].title,用';'分隔

  3. 将第二个字符读入Song[i].durMin,用';'分隔

  4. 将第三个字符读入 Song[i].durSec,由换行符分隔

编译并运行代码后,我得到这个作为我的输出:

~/project2Test> ./test
What is the file location?: songs.txt

然后程序在这里挂起,我必须 ctrl+C 退出

首先,我做错了什么? 其次,我该如何解决我搞砸的问题?

另外,作为类规则的注释,我不允许使用除文件名之外的任何字符串。除此之外,所有单词都必须是字符。

【问题讨论】:

  • 这应该可以帮助您顺利上路:stackoverflow.com/questions/1120140/…
  • "all words must be chars" 你的意思是char arrays 对吧?
  • “我不允许使用除文件名之外的任何字符串” 我真的不知道教你的目的是什么 ;(
  • 您正在阅读来自cin,而您应该阅读来自inFile。因此,您的代码正在等待来自控制台的输入。使用inFile.getinFile.getLine()

标签: c++ arrays struct char


【解决方案1】:

调试器绝对是解决此类问题的好东西。

您的挂起问题正在发生,因为在您的 get_data 函数中,您使用 cin.get 指示您的程序从标准输入文件获取输入。您打算使用您定义的文件,“inFile”而不是标准输入 cin。

顺便说一句,我不清楚为什么每次 for 循环迭代都将 i 递增两次。

【讨论】:

    【解决方案2】:

    使用 inFile.get() 代替 cin。您需要先将 inFile 传递给函数。

    在 for 循环中添加一个打印语句以查看发生了什么。未来可能会出现的问题是,如果您在 Windows 机器上并且有 \r\n 行结尾。 Unix 使用 \n,Windows 使用 \r\n

    【讨论】:

    • 但除非您以二进制模式打开,否则 Windows 会将 \r\n 序列转换为单个 char '\n'
    • 哦,这很酷。我不知道。上次..我确实使用了二进制模式,这是我的问题之一。感谢您的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2021-02-25
    • 1970-01-01
    相关资源
    最近更新 更多