c++ - need help reading file contents into an array C++
问题描述
I want to be able to do $> ./program file.txt 8 and then read the 8 values inside file.txt into an array
heres the code I have right now but it doesn't work
int main(int argc, char *argv[])
{
ifstream file;
int size;
int arr[size],val;
for(int i=0;i<size;i++)
{
cin>>val;
arr[i] = val ;
}
解决方案
据我了解,您想从文本文件中读取一些值。你可以这样做:
int main()
{
std::string textArray[8]; // array to store the data
std::fstream textFile; // creating a file object
textFile.open("text_file.txt", std::ios_base::in); // creating and opening a text file
if (textFile.is_open()) // check to see if file opened sucessfully
{
for (int a = 0; a < 8; ++a)
{
getline(textFile, textArray[a]); // using getline to get the values of the file
std::cout << textArray[a] << "\n";
}
textFile.close(); // closing the files after we're done using it
}
}
如您所见,我们打开了一个文件,并用于getline()
读取该文件的内容并将其存储在一个数组中。
推荐阅读
- arrays - python上的列表到字节转换
- google-apps-script - 以单元格更改为条件的 Google 表格单元格格式 (GOOGLEFINANCE)
- jenkins - Jenkins 声明式管道 - java.lang.NoSuchMethodError:没有这样的 DSL 方法“管道”
- sql - 努力从现有 SQL 数据库开始使用实体框架
- javascript - 我的 Blazor .NET Core 5.x“@inject IJSRuntime JS”语句从 Visual Studio 2019 收到 CS0246 错误
- php - 如何获得functions.php中的函数有回声的次数?
- javascript - 为什么 Javascript 会改变属性的值?不将其传递给另一个变量
- ios - Swift Json 将嵌套数组/字典解码为平面模型
- python - 使用 pytest 在单元测试中避免或绕过多个装饰器
- c# - 你如何配置 IRequestClient
和 IConsumer 使用 MassTransit.Multibus?