C++ 从文本文件读取数组
我有下面的文本文件,我有一个使用vector template类(称为x)创建的数组,我想在其中分配数组元素。用户输入n的值,根据n的值,使用vector template类创建的数组应该存储该数组的值 例如:如果用户输入5,x应该将元素的值存储在:legendre_root[5]中。 有人能建议我如何读取文件,以便存储特定n的数组元素吗。我可以使用push_back()将值提供给x,但在此之前,我需要在文本文件中查找数组 这是我尝试的代码:C++ 从文本文件读取数组,c++,file,C++,File,我有下面的文本文件,我有一个使用vector template类(称为x)创建的数组,我想在其中分配数组元素。用户输入n的值,根据n的值,使用vector template类创建的数组应该存储该数组的值 例如:如果用户输入5,x应该将元素的值存储在:legendre_root[5]中。 有人能建议我如何读取文件,以便存储特定n的数组元素吗。我可以使用push_back()将值提供给x,但在此之前,我需要在文本文件中查找数组 这是我尝试的代码: while(fin1.getline(')') &a
while(fin1.getline(')') && fin2.getline(')'))
{
fin1.getline([n]);
fin2.getline([n]);
fin1>>score1;
fin2>>score2;
x = push_back(score1);
w = push_back(score2);
}
这里有一种方法。读取每行的第一个字符(假设
$legendre_roots
从行的开头开始),并查看它是否为$
。如果不去下一行。。。直到找到为止。然后将$
后面的文本读入字符串,查看它是否与数组名和所需索引匹配。如果没有找到,请重新启动
找到后,迭代已知次数(等于索引)将所有数据读取到数组中,同时清除其中的制表符和标点符号。以下是示例代码:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <limits>
int main()
{
std::istringstream iss(R"(
$legendre_roots = array();
$legendre_roots[2] = (
0.123213213213213,
-8.123213213213213);
$legendre_roots[3] = (
0.123213213213213,
8.123213213213213,
3.1232133213);
$legendre_roots[4] = (
0,
3.1232144444,
8.123213213213213,
3.1232133213);
)");
size_t n;
std::cout << "Enter N from 2 to 4: ";
std::cin >> n;
std::cout << std::endl;
char dollar_sign;
std::string array_name, search_name = "legendre_roots[" + std::to_string(n) + "]", delims("-.0123456789");
std::vector<std::string> array_elements(n);
while (iss >> dollar_sign)
{
if (dollar_sign == '$' && iss >> array_name && array_name == search_name)
{
iss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (size_t i = 0; i < n; ++i)
{
std::string line;
std::getline(iss, line, '\n');
size_t start = line.find_first_of(delims), end = line.find_first_not_of(delims, start);
array_elements[i] = line.substr(start, end - start);
}
break;
}
iss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
for (auto const &element : array_elements)
std::cout << element << std::endl;
return 0;
}
#包括
#包括
#包括
#包括
#包括
int main()
{
标准::istringstream iss(R)(
$legendre_根=数组();
$legendre_根[2]=(
0.123213213213213,
-8.123213213213213);
$legendre_根[3]=(
0.123213213213213,
8.123213213213213,
3.1232133213);
$legendre_根[4]=(
0,
3.1232144444,
8.123213213213213,
3.1232133213);
)");
尺寸;
std::cout>n;
标准::cout>美元(符号)
{
如果(美元符号=='$'&&iss>>数组名称和数组名称==搜索名称)
{
iss.ignore(std::numeric_limits::max(),'\n');
对于(尺寸i=0;i 你试过什么?这不仅仅是“文本文件”,这是PHP代码。我将此PHP转换为txt文件。如果用户输入0或1怎么办?用户必须输入2到64之间的数字。我不想在我的程序中使用文本文件,文本文件太大。我如何读取文本文件,然后将值存储在数组中?这只是一个示例。您可以用ifstream替换istringstream。您可以建议在线C吗++允许我使用文本文件进行输入和输出的编译器?这个编译器可以写入和读取文件:但我不知道如何将cin
传递给它,所以我在示例中对其进行了编辑我们需要在命令窗口中提供文件本身?我不能将文本文件上载到其中吗?