如何从文本文件中读取字符串类型(而不是数字),并将数据存储在c++中的数组中
how to read string type (not number) from a text file and store the data in array in c++?
程序将询问用户想要使用的数据文件的名称(完整路径)并打开该文件。然后它读取并存储数组中的数据?这就是我的代码的外观,但它没有给出任何输出。
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)
相关文章:
- 将从格式化文本文件读取的文本数据存储到链表
- 将线程中的数据存储到全局容器的最佳方法?
- 将数据存储在内存中以供以后访问
- 将一个阵列中的数据存储到另外两个阵列中不起作用
- 如何将函数的输出数据存储在文本文件中
- 将结构数据存储在循环缓冲区中
- 安卓中的Qt和应用程序数据存储
- C++ 将数据存储在对齐数组的中间
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 实现双链接列表,其中数据存储在堆上
- 是否有一种方法可以从文本文件中读取并将单个数据存储为不同的变量
- 了解字符数组初始化和数据存储
- 如何在C++中将字符串数据存储在字符串 2D 数组中
- 将数据存储在具有可互换 x/y 坐标的 2D 矩阵中
- 将文件中的数据存储到数组中
- 将数据存储到地图
- 保存和加载类数据存储在C 中的二进制文件中
- 将由结构构建的数组传递到将数据存储到文件中的函数
- 在这种情况下,将数据存储在诸如SQLite之类的数据库中,还是存储在平面文本文件中更好
- 将数据存储在char数组中导致变量周围损坏