如何从char数组中读取数字(int)值

时间:2016-09-18 14:01:15

标签: c++

) 我目前正在研究C ++中的文件和文件流

我的问题是:

我需要在文件中写入几个数字,并在从中读取数据后 - 只有那些数据,如果它可以被建模(%)4。 主要问题是,我从文件中读取数据后,将其放入"缓冲区"数组,所有数字值在char数组中转换为单个字符 - > " 100"分为' 1' 0' 0' 0'和" 89"例如,对于' 8'和' 9' 如何将它们再次拉到一起,这样字符就会变回数字(在100中不在' 1,' 0',' 0')并将它们放在新的数组中?

P.S。请尽可能简单:)我还在学习!

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main()
{
    int numbers [] = {1, 100, 2, 98, 22, 12, 72, 16, 50, 51};
    int array_size = sizeof(numbers)/sizeof(numbers[0]);

                    //Start of file writing
    ofstream To_file ("C:\\CodeBlocks\\My_projects\\Test_KD_Files\\1stFile.txt");

    cout<< "This numbers will be written in file: " <<endl;
    for (int start = 0; start<array_size; start++)
    {
    To_file<< numbers[start] << " ";
    cout<<numbers[start] << ", ";
    }
    cout<<endl <<endl;

    To_file.close();
                    //End of file writing

                //Start of file reading

    char buffer [50];
    int index = 0;

    ifstream Read_it ("C:\\CodeBlocks\\My_projects\\Test_KD_Files\\1stFile.txt");
    cout<<"Data from file: " <<endl;

        while (Read_it.getline(buffer, 50))
        {
        Read_it.getline(buffer, 50); //all read data will be set in array "buffer"

        cout<< endl <<buffer[index];

            while (index<50) 
            {
                if (buffer[index]%4 ==0) //check - does number can be devided by 4
                {
                    cout<<buffer[index]; //display mostly messed numbers and characters
                }
                index++;
            }

        }

    Read_it.close();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

getline继续读取一个空格,但在行尾字符处停止。所以getline不是你搜索的内容。

诀窍是使用&gt;&gt;操作员在到达空白区域或换行符时停止读取。然后我们使用atoi()将字符串转换为整数:

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main()
{
    int numbers [] = {1, 100, 2, 98, 22, 12, 72, 16, 50, 51};
    int array_size = sizeof(numbers)/sizeof(numbers[0]);

                    //Start of file writing
    ofstream To_file ("File.txt");

    cout<< "This numbers will be written in file: " <<endl;
    for (int start = 0; start<array_size; start++)
    {
    To_file<< numbers[start] << " ";
    cout<<numbers[start] << ", ";
    }
    cout<<endl <<endl;

    To_file.close();
                    //End of file writing

                //Start of file reading

    int NewNumbers[10];
    char buffer [50];
    int index = 0;

    ifstream Read_it ("File.txt");
    cout<<"Data from file: " <<endl;

    while(Read_it >> buffer)  // we use extraction >> operator to read until white space
    {
        NewNumbers[index] = atoi(buffer);
        index++;
    }

    for(int i(0); i < 10; i++)
        cout << NewNumbers[i] << ", ";

    cout << endl << endl;


    Read_it.close();

    return 0;
}