gpt4 book ai didi

c++ - 从文件中读取数字 C++

转载 作者:搜寻专家 更新时间:2023-10-30 23:57:11 25 4
gpt4 key购买 nike

我想从文本文件中读取数字。该文件包含以下数字。

3 5 7 9 20 25 30 40 55 56 57 60 62
1 4 7 11 14 25 44 47 55 57 100
-5 100 1000 1005
-12 1000 1001

空格分隔数字。我不得不写一些代码来阅读这个,但问题是读取行尾的数字不正确,我不知道如何正确阅读它们(CRLF 字符问题);有人可以帮我弄这个吗?这是我的代码。

标题基础.h

#include <iostream>
#include <fstream>
#include <string.h>
#include <cstdlib>
using namespace std;

class L
{
public:
int value;
};

class t
{
public:
L *line;
t(){
line = new L[10000];
}
};

class baza
{
public:
ifstream in;
ofstream out;
string lines;
char word1[1] ;
int wordint;
char tab[255];
int *tab2;

int x;
int y;
int z;
int a;
int b;
int c;
int ile;

int multiplier;
bool negative ;
int negative;
t *table;

base();
};

这里是base.cpp

#include "base.h"

base::base()
{
wordint=0;
a=2000;
b=0;
tab2 =new int [a];
x=0;
y=0;
z=0;

for(int i=0;i<a;i++)
{
tab2[i]=0;

}
multiplier=1;
negative =false;
negative1=-1;
lines="0";
ile=0;
in.open("in.txt"); //open file

do
{
getline(in,lines);
if(lines!="0") //how many lines is in the file
{
ile++;
}
} while(in.eof()!=true);
in.close();
tablica =new t[ile];
tab5 = new int[ile];
in.open("in.txt");

for(int i=0;i<ile;i++)
{
do
{
in.get(word1[0]);
if(word1[0]==45) // check if sign is negative
{
word1[0]=0;
negative=true;
in.get(word1[0]);
}
if(word1[0]!= 10) //check if not LF
{
if(word1[0]!=' ') //check if not space
{
tab[x]= word1[0];
x++;
}
}
if(word1[0]==' ') //if space then convert from char to int
{
y=x-1;
do {
word1[0]=tab[y];
wordint=atoi(word1);
wordint=wordint*multiplier;
tab2[z]=tab2[z]+wordint;
y--;
multiplier=multiplier*10;
} while(y>=0);
x=0;
multiplier=1;
if(negative==true) //check if negative
{
tab2[z]=tab2[z]*negative1;
negative=false;
}
z++;
c=z;
tab5[i]=c;
}
/**if(word1[0]== '10') //its not work but same as above only check if LF
{
y=x-1;
do{
word1[0]=tab[y];
wordint=atoi(word1);
wordint=wordint*multiplier;
cout<<"dupa";
tab2[z]=tab2[z]+wordint;
y--;
multiplier=multiplier*10;
} while(y>=0);
x=0;
multiplier=1;
if(negative==true) //check if negative
{
tab2[z]=tab2[z]*negative1;
negative=false;
}
z++;
c=z;
tab5[i]=c;
}*/

} while(word1[0]!=10);
for(int j=0;j<z;j++) //write to table
{
table[i].line[j].value=tab2[j];
cout<< table[i].line[j].value<<endl;
tab2[j]=0;
}
z=0;
}
}

最佳答案

您应该简单地组合示例如下:

您的代码看起来比您发布的代码更智能并且应该可以工作。

关于c++ - 从文件中读取数字 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com