Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checking for invalid characters. C++

Status
Not open for further replies.

sasar

Technical User
Dec 7, 2002
1
US
I need program in C++ to read the information from data file and check for invalid characters.The only valid characters will be numerals and white space.Valid characters needs to be printed out to the screen, keeping the same number of lines.
Sample of data file:

Sample Pressure Volume Mass Temperature
1 1 atm 100 liter 1000 g 300 K
2 2 atm 200 liter 500 g 450 K
3 1 atm 400 liter 200 g 900 K
Thank You !!!
 
You could use a translation matrix. Each character will be marked as legal or illegal. Then, loop round doing something like

Code:
int c = fgetc (instream);
if (legal[c]) fputc (c, outstream);
If you look at some of the implementations of islower etc, you will find that many systems use a lookup array like this. It is the simplest and fastest technique.
 
Better yet, use the C++ STL features to make your life easier.
Code:
#include <string>
#include <fstream>
#include <iostream>

std::ifstream infile;
std::string line;
int pos;

infile.open(&quot;datafile.txt&quot;);
while (infile){
    std::getline(infile, line);
    while ((pos = line.find_first_not_of(&quot; \t\r\n0123456789&quot;)) != npos){
    line.erase(pos, 1);
    }
std::cout << line;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top