c++ - 将 txt.-file 中不同行上的数字读取到 C++ 中的数组

标签 c++ arrays

为了解决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/

相关文章:

java - 包含 Java 对象的数组中的最大值

Javascript:从子字符串中查找数组中最相关的字符串

javascript - javascript 反转数组中一定数量的元素

c++ - 寻找最低值(value)。功能。错误 : Thread 1: EXC_BAD_ACCESS (Code =1, 地址 = 0x7fff5fc89000)

c++ - 多线程处理,同时保持部分顺序

c++ - 用于模块化 C++ 框架的 CMAKE

c++ - 处理对象问题

c++ - Bad_alloc 问题

javascript - array.sort javascript,在第 10 个人之后不排序

java - 在 Java 中将 String[] 插入到 String[] 中?