代码之家  ›  专栏  ›  技术社区  ›  wawaloo_17

将整数读入数组C++

c++
  •  -1
  • wawaloo_17  · 技术社区  · 7 年前

    我正在读一个叫做数字的文件。txt并将整数插入数组。我的代码只输出文件中的最后一个整数。

    //numbers.txt
    1
    10
    7
    23
    9
    3
    12
    5
    2
    32
    6
    42
    

    我的代码:

    int main(){
    ifstream myReadFile;
    myReadFile.open("/Users/simanshrestha/Dev/PriorityQueue/PriorityQueue/numbers.txt");
    char output[100];
    int count = 0;
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {
            myReadFile >> output;
            //cout<< output << endl;
            count++;
        }
        for(int i=0;i<count;i++)
        {
            cout << output[i];
        }
        cout<<endl;
    }
    cout << "Number of lines: " << count<< endl;
    myReadFile.close();
    return 0;
    }
    
    3 回复  |  直到 7 年前
        1
  •  1
  •   C.yixian    7 年前
    int main()
    {
        std::ifstream myReadFile;
        myReadFile.open("/home/duoyi/numbers.txt");
        char output[100];
        int numbers[100];
        int count = 0;
        if (myReadFile.is_open())
        {
            while (myReadFile >> output && !myReadFile.eof())
            {
                numbers[count] = atoi(output);
                count++;
            }
            for(int i = 0; i < count; i++)
            {
                cout << numbers[i] << endl;
            }
        }
        cout << "Number of lines: " << count<< endl;
        myReadFile.close();
        return 0;
    }
    

    试试这个。 atoi是一个将字符串转换为整数的函数。

        2
  •  0
  •   DeCastroAj    7 年前

    你也可以试试这个:和底部一样

    基本上,您需要定义一个“temp”或holder变量来存储数据。循环中的任何内容都会留在该循环中,这会导致范围解析,并在每次存储数据时覆盖数据,因为它根本不会退出。

    希望这有帮助!

    #include <fstream>
    #include <iostream>
    #include <cstdlib>
    #include <string>
    using namespace std;
    const string FILE = "your file name here";
    
    int main()
    {
        ifstream myReadFile;
        myReadFile.open(FILE);
        char output[100];
        int numbers[100];
        int count = 0;
        if (myReadFile.is_open()){
            while (myReadFile >> output && !myReadFile.eof()) //not stopping until we reach end of file
            {
                numbers[count] = atoi(output); //converts string to int
                count++;
            }
            for(int i = 0; i < count; i++)
            {
                cout << numbers[i] << endl;
            }
        }
        cout << "Number of lines: " << count+1 << endl; //total number of lines in file
        myReadFile.close();
        else{ cout << "Error: File name not loaded" << endl;}
        return 0;
    }
    
        3
  •  0
  •   edm    7 年前

    我可以冒昧地猜测一下,您的代码得到了所有数字的总和,并且它保存在数组的第一个元素中吗? 我还可以猜一下,您是否希望将文本文件中第一行的编号保存在数组的第一个元素中?第二元素中的第二行等等?

    如果是,则可能需要更新以下代码:

    myReadFile >> output;

    myReadFile >> output[count];

    我很确定这在C语言中会起作用,并假设这在C++中也会起作用

    更新日期: 另一个需要添加的内容是使用如下2D数组:

    char output[100][5]; //assuming our number is at most 5 char long