如何从文本文件中读取字符串类型(而不是数字)并将数据存储在c ++中的数组中?

时间:2013-12-08 23:59:07

标签: c++ arrays

程序将询问用户他们希望使用的数据文件的名称(完整路径)并打开文件。然后它读取并存储数组中的数据?这是我的代码看起来的样子,但它没有给出任何输出。

int main()
{
    int numofbooks = 0;

    std::string listbooks[25];

    std::ifstream readlib;

    std::cout << "This is a program that shows the title of books in different ways" << std::endl;

    std::cout << std::endl;

    clearlibrary();

    outputlibrary();

    readlibrary(listbooks, numofbooks);

    outputlibrary1(listbooks, numofbooks);

    return 0;
}

void readlibrary(std::string listbooks[], int numofbooks)
{
    const int file1 = 100;

    char readfile1[file1];

    std::cout << "Please enter the file name to read? " << std::endl;
    std::cin >> readfile1;
    std::ifstream readlib;
    std::string line;
    readlib.open(readfile1);

    int counter = 0;
    while (getline (readlib, line))
    {
        listbooks[counter] = line; counter++; if (counter>=25) {break;}
    }

    numofbooks = counter;

    readlib.close();
}

void outputlibrary1(std::string listbooks[], int numofbooks)
{
    std::cout << "List of books in your array" << std::endl;

    for (int i = numofbooks -1; i >= 0; i++)
    {
        std::cout << listbooks[i] << std::endl;
    }

    std::cout << std::endl;
}

void outputReverse(std::string listbooks[], int numofbooks)
{
    std::cout << "List of books in your array in reverse order" << std::endl;

    for(int i = numofbooks - 1; i >= 0; i--)
    {
        std::cout << listbooks[i] << std::endl;
    }

    std::cout << std::endl;
}

2 个答案:

答案 0 :(得分:1)

void readlibrary(std::string listbooks[], int numofbooks)未按预期返回numofbooks - 请使用引用:

void readlibrary(std::string listbooks[], int& numofbooks)

你说没有输出。它至少打印出“阵列中的书籍列表”吗?

P.S。这也可能是错误的(注意增量):

for (int i = numofbooks -1; i >= 0; i++)

答案 1 :(得分:0)

for (int i = numofbooks -1; i >= 0; i++)

如果用户输入numofbooks的正数,则会导致无限循环和未定义行为以访问超出界限的地址。

您需要将其更改为:

for (int i = 0; i < numofbooks; ++i)