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

how to read string type (not number) from a text file and store the data in array in c++?

本文关键字:数据 存储 c++ 数字 数组 文件 文本 读取 字符串 类型      更新时间:2023-10-16

程序将询问用户想要使用的数据文件的名称(完整路径)并打开该文件。然后它读取并存储数组中的数据?这就是我的代码的外观,但它没有给出任何输出。

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;
}

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

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

你说没有输出。它至少会打印"数组中的图书列表"吗?

附言:这可能也是错误的(注意增量):

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

如果用户为numofbooks输入正数,则会导致访问越界地址的无限循环和Undefined Behavior。

您需要将其更改为:

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