just a little problem

Pages: 12
Hello boys, I am trying to make a program that inputs a positive integer n, and a text file, and outputs in reverse order the characters placed on the n-th line of the text file.

I have this so far :
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
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n;
ofstream outfile;
ifstream infile;
string filename;
fstream in_stream;

cout << "enter the input file name: ";
cin >> filename;
cout<< "input the line number ";
cin>> n;
infile.open(filename.c_str());

outfile.open("myoutput.txt");


while (!in_stream.eof())
{
string line;
in_stream.getline(line);
cout<<line;
}
in_stream.close();
return 0;
}


for the reversing of the line i can use somethink like this :
1
2
3
4
5
6
int size = line.length();
while (size >= 0)
{
cout << line[size];
size--;
}

Now my question is what else should i write to become useful the entire code?
This material havent been taught yet, but I want to make it :D, so any help will be very appreciated;)
Well you will need to count the lines in your while loop and use an if statement to do the line reversal code when you get to line n.

Also, what exactly is fstream in_stream for? You already have an ofstream and an ifstream? Perhaps you should read a bit about file I/O.

http://cplusplus.com/doc/tutorial/files/

Hope this helps.
Thank you Xander314, it helped me, its more clear for me now.
While I was reading it I get another idea:

I can use that to display the text in the console,after that,as you said, I will use a loop to find the exact line which have to be reversed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}


The problems are:
1: That code above doesnt work (I think)
2:I dont know how exactly to count the lines in the text, and to take the right one. Yes I know it should be something like "for (int i=1;i<=n;i++)" but where should I put this?
I would just put it in the same loop as the reading from the file part. If you initialize a counter variable to 0 before the loop and increment it at the start of each loop. That way it will be 1 on the first loop, 2 on the second loop and so forth.

This will work therefore, provided each iteration of the loop reads exactly one line of the file. What is that function getline? Have you defined it yourself? Otherwise you may be trying to use to member function getline of std::ifstream, which you can read about here for more detail - http://cplusplus.com/reference/iostream/istream/getline/.

PS: You could do a separate for loop, but by doing it as I suggested above, you can avoid necessarily repeating lines of code.
I toke the last code directly from the link which you gave me, because I think it will be easy if I illustrate the file in the console and then count the lines.But this code doesnt work ?!?!Every time it displays "Unable to open file".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
for (int i=0;i<=n;i++)
{
if (i==n)   cout << i << endl;
}  
  }
    myfile.close();
  }


do you mean something like this?
Last edited on
That wasn't how I was suggesting you did it, but it should work fine.

However, on line 6 you have written i=n. '=' is the assignment operator so it will assign the value of n to i. What you want to use is the comparison operator '==' to compare i and n.

As for the file never opening, is there definitely a file called "example.txt". You could also try an absolute path to the file, e.g. "C:\\examples.txt" (then you would have to put examples.txt on your root drive). Otherwise it might depend on your IDE exactly where the program looks for the "examples.txt" file.
About the "=" i wrote it by mistake.I corrected it.
I didnt get your idea about the absolute path.Where should I put it?
Last edited on
When you try to open the file:
std::ifstream myfile("examples.txt");
I suggest you type in the full path of the "examples.txt" file. It's a pain. However, if you do this and the problem is solved, you know that the problem is that the program wasn't looking for the file in the right place (if you tell me your IDE I may be able to suggest where to put the file). If the problem persists then you know it is some other file error.

PS: Remember to escape your backslashes: '\\' = \. So you might put something like "C:\\users\\jennifer\\documents\\programming\\examples.txt" or wherever you have put the file.

It's not a great fix, but try it and let me know if it fixes it :)
Still doesnt work.I work with Dev-c++.
Anyway, I think its not necessary to display the text in the console.Am i right?
Well that's really up to you. It depends what you want your program to do.

However, does the program still always say "Unable to open file". Successfully opening the file is pretty crucial to your application, I should think.

EDIT: It would be easier to see what's wrong with your code if you post an up to date version of the whole thing along with the output when you run it.

PS: In my opinion, you should find a more up to date IDE. Unless you are using wxDev C++, then your IDE is no longer bug fixed or updated, I believe. Here's a detailed article about why not to use it :P http://www.cplusplus.com/forum/articles/36896/

(I suggest Visual C++ Express - it's really good!)
Last edited on
Thanks for the advise :).
So what i want to do is to make a program which asks the user to input a number of a line.So the user chooses line 3.The program should take line number 3 from a file with name for example "example.txt", to reverse it and to display it.Thats all
OK. Can you post your full code so far (as long as you don't mind sharing all the code), as this would make it easier to see why it isn't working (assuming it still isn't working).
ok here it is.I tried to use the previous code (with which I had problems with opening the file) instead of this one :
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
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int n;
ofstream outfile;
ifstream infile;
string filename;


cout << "enter the input file name: ";
cin >> filename;
cout<< "input the line number ";
cin>> n;
infile.open(filename.c_str());


while (!in_stream.eof())
{
string line;
in_stream.getline(line);
cout<<line;
}
in_stream.close();
return 0;
}


With this I want to input the file in the compiler.
Once I do it I should use a loop to count the lines and to take the right one, after that to reverse it.I still dont know where to put that loop, but I should connect the compiler and the file first.
Right. So firstly, between lines 16 and 18 you should check the file has opened correctly and if it hasn't, display and error message and end the program.

Next, you need a counter variable like int line_number = 0; defined before your loop. Then increment it at the start of each iteration of the loop. It represents the line number.

Then you can check in each loop if it equals n, and if so you do your backwards display thing.

NB: If you understand this and do it the way I suggest, there is no need for a for loop.

Hope this helps.
Ok I think I get the idea, wait a minute I will try it...
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
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
int n;
ofstream outfile;
ifstream infile;
string filename;


cout << "enter the input file name: ";
cin >> filename;
cout<< "input the line number ";
cin>> n;
infile.open(filename.c_str());

if (infile.fail())
{ cout << "Error opening " << filename << "\n";
return 1;
}
else {
while (!infile.eof())
{
int line_number = 0;
for ( line_number=0;line_number<=n;line_number++){
cout<<line_number;
}
int size = line_number.length();
while (size >= 0)
{
cout << line_number[size];
size--;
}

}
}
infile.close();
system ("pause");
return 0;
}

Thats all I could make.Where is my mistake.I fell like my mind will explode :D
Last edited on
This error is because you use 'in_stream' on lines 23 and 31, which you have not defined. Your file is called 'infile', not 'in_stream'. So you should be using 'infile'. You had defined something called 'in_stream' before, but you correctly removed it as it was not necessary.

There is another problem, however with this code. I'll happily explain it to you if necessary, but it's probably better if you can work it out for yourself. It's to do with the variable line_number which is supposed to count up with each iteration through the loop.

If you are comfortable with breakpoints and debugging, try debugging this program and adding a watch for the line_number variable. Otherwise, just have a look at the code and think about what will happen to this variable.

If you really can't work it out then I'll tell you - it's just that it's good practice to think about these things yourself :)
I know that line_number is only the number of the line, and even if I make it work, because of this
cout<<line_number it will output just a number.I cant find a way to take the line not the number

p.s. I cant find a way.Ok whats your idea?Are you still here?
Last edited on
OK. When I did my last post I missed a detail of your most recent code segment and my advice wasn't exactly what I should have put... sorry ;)

Anyway, it looks like you're getting bogged down in quite a few loops, where you really only need one loop. Either a for loop or a while loop would work, but I think a while loop would be easier. The key point is that you only need one loop.

Here is a code segment. I have decided to give it to you rather than explain with words as it will be easier. However, it's really important you type it up yourself and so forth so that you understand how it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int line_number = 0;
while (!infile.eof())
{
   line_number++; // we do this at the start of the loop so that we start with 1 and not 0
   
   string line;                            // these two lines read a line of data from the file you wrote 
   in_stream.getline(line);        // them yourself earlier, but then got rid of them.

   // now you need to check if the line number is the one you want
   // think about how to check this with an "if" statement
   // if it is the line_number you want, you now need the second inner loop
   // to display the string backwards
   // see if you can work this bit out yourself
   // you've already almost written this bit in various places
   // just see how you go!
}


PS: If you have done functions, you could simplify the structure by writing a separate function to print a given string backwards. If you aren't sure about this, though, just don't worry about it :)

Good luck! Let me know if you continue to have difficulties.
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
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
int n;
int line_number = 0;

ofstream outfile;
ifstream infile;
string filename;


cout << "enter the input file name: ";
cin >> filename;
cout<< "input the line number ";
cin>> n;
infile.open(filename.c_str());

if (infile.fail()) 
    { cout << "Error opening " << filename << "\n";
    return 1;
    }
else {

int line_number = 0;
while (!infile.eof())
{
   line_number++; 
   string line;                           
   infile.getline(line);        

if (line_number==n){
int size = line.length();
while (size >= 0)
{
cout << line[size];
size--;
}
}
}  
}

infile.close();
system ("pause");
return 0;
}

thats what I did, but I am not sure if it should look like that because line_number is still the number of the line, not the actual line.
p.s.Now is the problem with the line corrected ? int size = line.length();
It gives me the following errors :

[Warning] In function `int main()':

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::getline(std::string&)'


candidates are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize, _CharT) [with _CharT = char, _Traits = std::char_traits<char>]


std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]


Last edited on
Pages: 12