New to c++ displaying file contents to console

Pages: 12
Hello, I am new to c++ and need some help understanding how a bit of code works.
I was given a segment of code:

1
2
3
4
5
char ch = 0;
while( infile.get( ch ) ) {
       		
			cout.put( ch );
		}


The code reads my file and displays it in the console. I understand that it is reading character by character but i do not understand how it properly outputs it in the proper format. By this i mean that where there is an enter down it properly displays it entered down. I want to add numbers to the beginning of each line so i had tried creating a counter inside of the while loop but what this did was put a number before each characyer and the formatting was messed up (everthing was on one line). This is what i had tried:

1
2
3
4
5
6
7
char ch = 0;
    while( infile.get( ch ) ) {
        ++count;
		cout << count;
		
			cout.put( ch );
		}



Any help is appreciated, Thank you.
Certain characters have special meaning. The one you are looking for is called the "newline" or "linefeed" character, and it is expressed in C and C++ as '\n'.
1
2
3
4
5
6
7
8
9
10
unsigned linenum = 1;
char ch = '\n';
do {
  cout.put( ch );
  if (ch == '\n')
  {
    cout << linenum << ": ";
    linenum++;
  }
} while (infile.get( ch ));

Hope this helps.
Thanks...I have numbers but for some reason i have a weird number that appears between the number and the text in the file. The number that appears is the same .... 6A73CACC

so basicly iim getting this

1: 6A73CACC#include <vector>
2: 6A73CACC#include<iostream>
3: 6A73CACCint main (string one, string two)
4:6A73CACCif (one == two)

you get the idea..
Thanks
Post your code.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 char ch = 0;
    while( infile.get( ch ) ) {
        if (ch=='\n')
		{
			cout << count << ": " << cout.put( ch ) ;
    ++count;
		}
		//else if (ch=='//')
		//{
		//	while (ch!='\n'){
		//		cout << "test";
		//	}
		//}
		else
		{
cout.put( ch );
		}

As i explained above it places a werid number...it did not display this before i added in the number lines. Also if you are wondering what i am trying to do thats is currently commented out, i am trying to make the program not output the comments to the console

Thanks
Where is count declared and initialized?

I think it is likely that you have a function named count somewhere in the code? (The STL comes with a count() template function in <algorithm>.)

I prefer variables with more explict names than just "count". What is it a count of?
"line_number" or "linenum" or "linecount" or "nlcount" or "lineindex" or somesuch... notice how each one indicates that it is the index/count/number of the current line?

Hope this helps.
this is only a segment of the code that i know is causing the problem ( i accidentally forgot to include at the top that i created the count varible... all i did was:

int count =0;

Thanks for the suggestion about varible naming and possible code fix.
Last edited on
You know, you would probably have a much easier time if you read the file line-by-line instead of character-by-character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string line;
while (getline( infile, line ))
{
  // Do what you will to remove comments or otherwise process the line here
  // for example:
  string::size_type pos = line.find_last_of( "//" );
  if (pos != string::npos)
    line.erase( pos );
  // Of course, when dealing with C/C++ source code, you must be a bit more 
  // careful than that. (You have to consider the possibility of string literals.)
  // Additional processing may also require some state from loop to loop. For
  // example, removing /* ... */ type comments must consider that the comment
  // spans more than one line.

  cout << line << endl;
}

If you want, I'll post a short C++ program I wrote a while back to extract string literals from C/C++ source code; if you are doing processing of that kind it may help you somewhat.
The string literals from c++ source code is exactly what i need to see.... I understand if you don't want to paste all of your code but if you could kinda step me through how to be able to code it would help me alot

Thanks
Extracting string literals from C/C++ source is often a "test yourself" or homework kind of activity.

Is this homework? (Even if it isn't, you will be much more satisfied if you solve it yourself.)

I will be glad to help as appropriate.


To get started, I did mine by reading line-by-line, but these kinds of algorithms are typically done as you started out (character by character). Either way works.

As you go, you need to count instances of the newline to know on what line the literal is encountered. You could also count characters if you like.

You must find and match all instances of the double-quote character (" ) that are not:
  ■ in a comment
  ■ explicitly quoted
  ■ implicitly quoted
This means that your code must keep track of these conditions.


Comments
All comments in C/C++ are initiated with the 'forward-slash' character (/). Hence, whenever you encounter this character, you need to read the next character to decide whether or not you are entering a comment. If the next character is another forward-slash, then just read characters until you hit the end of the line and then continue normally. If the next character is an asterisk, then you must read characters until you find the end of the comment (character sequence of */).

String literals cannot, by definition, appear inside commentary.


Explicit quotes
The next thing you need to worry about is explicitly-quoted things. An explictly-quoted item is preceded by the escape character, or 'back-slash' (\).

An escaped double-quote is never counted as a string delimiter. \"

An escape may escape itself. (Hence, \\" does contain a string delimiter.)

An escape may escape the end of a line. That is, a string literal may span multiple lines! For example:
1
2
3
4
const char* instructions = "usage:\
  foo FILENAME\
  \
  Report the amount of fooey in FILENAME.";
These kinds of strings should be understood to be the same as:
 
const char* instructions = "usage:\n  foo FILENAME\n  \n  Report the amount of fooey in FILENAME.";
Keep in mind that a trailing back-slash may occur outside of a string literal as well, and should be accordingly ignored (the same as anything other than the above items that is explicitly escaped).


Implicit quotes
The last thing you need to worry about is the valid sequence '"', which C programmers tend to write as '\"', but is perfectly valid either way. This may occur as part of a multi-character constant, meaning you could get a character literal in source code that looks like '12"4' or some other such nonsense. So your code will have to recognize unquoted character delimiters and treat them as strings (except that they are not printed or the like).

My code does not handle multi-char constants very well. It could, but I didn't think of the possibility when writing the code. I suppose I'll have to amend it...


The organization of your program should, then, start assuming normal state. If it finds a comment, read to the end of the comment. If it finds a string, then output the current line number (and any other information you want, such as filename and/or column number), then begin displaying characters until the string is properly terminated. Et cetera until EOF.

Hope this helps.
WOW... Thank you SO much

Thanks for teaching me how to write the code instead of just giving me the answer
I am working on the statment to not display the comments... for some reason im getting an infinate loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
char ch = 0;
    while( infile.get( ch ) ) {
         if (ch==47)
		{
			while (ch!='/n'){
				cout << "test";
			}
		 }
		else if (ch=='\n')
		{
			cout << counter << ": "  << cout.put( ch ) ;
    ++counter;
		}
		
		
		else
		{
cout.put( ch );
		}




the program should display the word test until it hits the new line...but it seems to just constanly loop...Thanks
Last edited on
closed account (j3bk4iN6)
how about putting the input inside the while loop and have while(ch!= 'q') because I think its an infinite loop because the while is always true. Or put a break in it
Last edited on
Line 5: ch will never be equal to '/n'. (Because you mean to have '\n'.)

Also, line 3: ch==47 == bad. Use the character directly, as: ch=='/'. It is more readable and it assumes nothing about the underlying character set.

Watch your indentation. For example, you have lines 9 and 16 indented much further than line 3, even though they all have the same importance. You might also want to consider using a switch statement instead of a bunch of if..else statements.

When you compile, make sure to turn on all warnings and use the strictest language standards possible.
Last edited on
I am also struggling with this problem. I have been working on it literally all day and cannot for the life of me figure it out.
I don't know why introductory programming course assignments often include this problem. It is not trivial.

It might be enough for your professor to simply read a file and find every matching pair of " s (but not \" ) and print everything in between.
closed account (j3bk4iN6)
if you can't reproduce the code, then you get an F
@abilify
Don't screw around with other people's education. If you can't give useful, non-perfidious commentary, then I'll ask that something be done about it.

It is really unpleasant to ask for help with something you know next to nothing about, and be told all kinds of useless, unhelpful, and incorrect stuff. This forum wasn't created to hinder learning.

So STOP.

@new2cpp & th3pr0f37
Read one character at a time.
If you find a '\\', you need to ignore the next character (whatever it may be).
If you find a '\"', you need to know whether you are starting or stopping a string literal.
If you are reading a string literal, you need to print each character you read.
If you are not reading a string literal, you should not print anything.

See if you can get that far. After that you can begin adding other conditions to handle weird stuff. I'll help you along the way. th3pr0f37 - I'm watching your thread too.
Thanks a lot for the help Duoas. I still feel like I am making zero progress with this but your support is great.
So I have tried and tried for hours but feel like I am getting nowhere. Here is my code so far... If anyone can help it's greatly appreciated.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//test comment1
/*
test comment 2
*/

#include <iostream>
#include <fstream>
using namespace std;

int main() 
{
	char filename[100];
	int lineNum = 0;

	cout << "Please enter a filename: ";
	cin >> filename;

    ifstream infile(filename);

    char ch = 0;
    while(infile.get(ch)) 
	{
		if (ch=='/')
		{
			infile.get(ch);
			if (ch=='/')
			{
				while ((infile.get(ch)) && (ch!='\n'))
				{
					//Does not print line because of comment
				}
			}
		}
		else if (ch=='/*')
		{
				while ((infile.get(ch)) && (ch!='*/'))
				{
					//Does not print line because of comment
				}
			
		}
		else if (ch=='"')
		{
			while ((infile.get(ch)) && (ch!='"'))
			{
			cout << '"' << cout.put(ch) << '"';
			}
		}
    }

	cout << lineNum;

    return 0;
}
Pages: 12