[英]How to read number (int) values from char array
;)我目前正在研究C ++中的文件和文件流
我的問題是:
我需要在文件中寫入幾個數字,然后從文件中讀取數據-如果可以按4 對數據進行建模(%),則僅該數據。主要問題是從文件中讀取數據並將其放入“緩沖區”之后數組,所有數字值都在char數組中轉換為單個字符->“ 100”拆分為“ 1”,“ 0”,“ 0”和“ 89”,例如拆分為“ 8”和“ 9”再次組合在一起,這樣字符將轉換回數字(以100為單位,而不是'1,'0','0')並將它們放入新數組中?
附言:請盡可能簡單:)我還在學習!
#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;
}
getline甚至繼續讀取空格,但在行末字符處停止。 因此,getline不是您要搜索的內容。
訣竅是使用>>運算符,當到達空白或換行符時,該運算符將停止讀取。 然后我們使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.