Reputation: 193
How to read integers from the following text file containing symbols, numbers and maybe alphabets?
I have the following text file
@
100:20 ;
20:40 ;
#
@
50:30 ;
#
@
10:21:37 ;
51:23 ;
22:44 ;
#
I have tried the following codes :
int main()
{
std::ifstream myfile("10.txt", std::ios_base::in);
int a;
while (myfile >> a)
{
std::cout<< a;
}
return 0;
}
and
void main()
{
std::ifstream myfile("10.txt", std::ios_base::in);
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int n;
while (iss >> n)
{
std::cout << n ;
}
}
}
All I get is a garbage value of int variable (or the initial value if I initialize it )
How to solve this?
Upvotes: 0
Views: 484
Reputation: 7472
You can try splitting each line into separate tokens delimited by the colon character:
int main()
{
std::ifstream myfile("10.txt", std::ios_base::in);
std::string line;
while (std::getline(myfile, line))
{
std::istringstream iss(line);
std::string token;
while (std::getline(iss, token, ':'))
{
std::istringstream tss(token);
int n;
while (tss >> n)
{
std::cout << n << std::endl;
}
}
}
return 0;
}
This should print:
100
20
20
40
50
30
10
21
37
51
23
22
44
As per this comment, I recommend a more robust parsing algorithm that respects the unique structure of your files.
Upvotes: 2
Reputation: 12178
Try skipping bad character one after another
Something like:
while (!in.eof())
{
int a;
in >> a;
if (!in) // not an int
{
in.clear(); // clear error status
in.ignore(1); // skip one char at input
}
else
{
cout << a;
}
}
Upvotes: 0