I want to write a program that reads a file and calculates the sum of all integers in the file. In this file, each line has only string or integers, it cannot have both of them.
I wrote the program to read each character of each line, and if it's an ASCII code between 48-57 then use the extraction >>
operator to save it, and do it again until EOF.
But, my issue is, when I read the first character of a line, if its a number then I lose the first digit of that number.
What can I do? I also tried using seekg()
, but it couldn't help me.
//A program that read file and calculate sum of numbers in file
#include <iostream>
#include <fstream>
#include <string.h>
int main ()
{
// decalre File path string to store path of file
std::string FilePath;
//recive from a user
std::cin>>FilePath;
//FilePath = "\""+ FilePath + "\"";
//mine guide
std::cout<<FilePath;
//declare Infile object of input stream for only read file
std::ifstream InFile ;
//open file
InFile.open(FilePath.c_str() , std::ios::in);
//inser if condition if file does not opened
if(!InFile)
{
std::cerr<<"can not open file ";
return 1;
}
//what the hell is that i forgot
std::string FileString ;
//decalre char type check char to check the line start with number or charater
char checkChar {};
//declare NUminFilie to read Nums in file
int NumInFile{};
// declare for calcualte sum of Nums in File
int SumOfNumInFile{};
//declare In vain string to go to next line in file
std::string InVainString ;
int counter = 0;
std::cout<<"befot while\n";
// insert a boolian variable falg to avoid back cursor if number is in begening of file because
bool flagNotAtFirstOfFile = false;
while (InFile.get(checkChar))
{
std::cout<<"get\n";
std::cout<<(int)checkChar<<std::endl;
if((((int)checkChar>=49)&&((int)checkChar<=57)))
{
std::cout<<"if char is done";
if(flagNotAtFirstOfFile)
{ std::cout<<" seekg is done "<<std::endl;
InFile.seekg(,std::ios::cur);
}
else
{
InFile.seekg(0,std::ios::beg);
flagNotAtFirstOfFile = true;
}
InFile>>NumInFile;
std::cout<<NumInFile<<std::endl;
SumOfNumInFile+= NumInFile;
}
// insert if condition to if checkChar read space character between 2 line number continue and do not read line
else if ((int)checkChar ==10)
{
continue ;
}
else
{
InFile.seekg(0,std::ios::cur);
std::getline(InFile,InVainString);
std::cout<<"getline :"<<InVainString<<std::endl;
}
//std::cout<<"getline :"<<InVainString<<std::endl;
//InFile.peek();
}
std::cout<<SumOfNumInFile;
return 0;
}
The input file is like this:
232300
675
khobi
chekhabar
233
34340
hjhkjh
6757
876876
hehehhe
1100
end