Seg Fault and not sure why?

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
#include <iostream>
#include<fstream>
#include <ctime>
#include <string>
#include <unistd.h>
 using namespace std;

 string  readandtype(string fn){
 ifstream myrfile;
 string lines;
 myrfile.open(fn.c_str());
 if(myrfile.is_open()){
        while(!myrfile.eof()){
        getline(myrfile,lines);

        for(int i = 0; i <lines.size();i++){
        cout<<flush;
        usleep(100000);
        cout <<lines[i];
        if(i == lines.size() -1 ) {
        cout<<endl;
        }
        }
        }
        myrfile.close();
        }


 }

 int main() {
 string fn;
 cout << "Enter FileName: ";
 cin >> fn;
 readandtype(fn);

 return 0;
 }



not sure why I'm getting a seg fault all I'm attempting to do is type out a file. Basically have each char of the file typed out one after the other. I feel like it has something to do with my 4 loop index going to far.
Last edited on
Line 9,
 
string readandtype(string fn)

the function readandtype() is defined as returning a string. But no value is returned from the function.

If it doesn't need to return anything, make the type void instead of string. Or if you did want to return something, make sure the function will always return a value, e.g. add return ""; at line 28.


Also - though not the cause of the seg fault, don't loop on eof(). Instead put the actual input operation as the loop condition.


Minor comment. Instead of this inside the for loop,
1
2
3
        if(i == lines.size() -1 ) {
        cout<<endl;
        }

just put
 
cout<<endl;
after the end of the for loop.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void readandtype(string fn)
{
    ifstream myrfile(fn.c_str());
    
    if (!myrfile)
        return;

    string lines;
            
    while (getline(myrfile,lines))
    {
        for (unsigned int i = 0; i <lines.size(); i++)
        {
            cout << flush;
            usleep(100000);
            cout << lines[i];
        }
        cout << endl;
    }
          
}
Last edited on
Ah so not returning a string cause the seg fault? Thanks for the help and advice works perfectly.
Topic archived. No new replies allowed.