I am trying to read from a file which contains some code. My goal is to separate tokens and display them. I am writing code in c++.
For Example,
If input is:
void main()
{
int n;
}
Output should be
Keyword void
keyword main
separator (
separator )
separator {
keyword int
identifier n
separator ;
separator }
Now my problem is that
i am trying to read from the file using %26gt;%26gt; operator
i.e
char s;
ifstream infile;
infile%26gt;%26gt;s
This fragment of code reads the data from the file character by character. The %26gt;%26gt; operator in c++ will not consider whitespaces. So as soon as it completes reading 'void' it is neglecting whitespace and start reading 'main'. So it is taking 'voidmain' as a single string and giving output as
identifier voidmain
What should i do to check for whitespace between the 'void' and 'main'
so that i can get the correct out put
keyword void
keyword main
Can u please help me out
Regards,
Prudeesh C Makkapati,
Graduate Teaching Assistant,
Computer Science Dept.
University of Alabama in Huntsville
How to recognise whitespaces in c++ by using '%26gt;%26gt;' operator. I kknow that'%26gt;%26gt;' will neglect spaces.
You're probably reading in one character at a time.
Use strings (STL).
#include %26lt;string%26gt;
string s;
ifstream f;
"f %26gt;%26gt; s;" will read in one word at a time.
Reply:You could either use the functions
get() // returns the next character
get(c) // puts next character in c
getline(s, n, t) // gets n number of characters up until t, use t=' ' (space), puts result into string s. t is not included in s
get(s, n, t) // like getline except leaves t on the stream
Or, use the manipulator 'noskipws' do not skip whitespace.
infile %26gt;%26gt; noskipws; // after this is will skip whitespace
so you could use the line
infile %26gt;%26gt; s; // afterwards.
If you need to change it back, use
infile %26gt;%26gt; skipws;
gardenia
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment