为了解决Euler Project 8在不求助于“大数字”库的情况下,我想读取 txt.-file 中的单独数字以分隔数组中的点。 txt.-file中的数字排列如下:
094239874......29837429837 [50 of them],
192319274......12837129873 [50 of them]
这样总共有 20 行 50 位数字,全部由 enter 分隔。所以我正在尝试编写一个程序,将第一个数字写入数组中的第一个位置并继续这个过程(注意空格)直到第 1000 个数字。我曾尝试在教程和其他地方的网上找到解决这个问题的方法,但我无法让它适用于这个特定的例子。到目前为止,我有类似的东西
int main() {
int array[999];
string trial[999];
ofstream myfile;
myfile.open ("example.txt");
for(i=1 ; i<=1000 ; i++) {
myfile >> trial;
// Somehow convert string to int as well in this loop?
}
最佳答案
您可以尝试这样做(首先将文件内容读入 string
,然后将每个 char
转换为 int
,顺便说一句,您应该使用 vector<int>
而不是原始数组):
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
string total;
ifstream a_file("data.txt");
while (getline(a_file, str))
total += str;
vector<int> vec;
for (int i = 0; i < total.size(); i++)
{
char c = total[i];
int a = c - '0';
vec.push_back(a);
}
}
关于c++ - 将 txt.-file 中不同行上的数字读取到 C++ 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917627/