using getchar() to get characters and save them into file with new line for each time c++

StackOverflow https://stackoverflow.com/questions/21553794

  •  06-10-2022
  •  | 
  •  

Question

As a beginner in c++, I was trying to get input characters using getchar() and save them in separate lines in a file without changing old content of that file. but I can't put those lines separately

void Record()
{
    system("stty raw") ;
    string line,old,s ;
    char charflow ;
    ifstream in ("Savefile");

    while(in >> s)
        old+=s ;
    while(charflow = getchar(), charflow!=char(13) ){
        line.push_back(charflow) ;
    }

    ofstream out ("Savefile") ;
    out<<old<<"\n"<<line;
    system("stty cooked") ;
} 


int main(int argc, char*argv[])
{
    cout << "put line 1: "  ;
    Record() ;
    cout << endl ;
    cout << "put line 2: " ;
    Record() ;
    cout << endl ;
    cout << "put line 3: " ;
    Record() ;
    cout << endl ;
}

The file looks like this:

line1line2

line3
Was it helpful?

Solution

Change

old += s + "\n"; // because when s is added to old it is just a string not "\n" (the line break) is added.

So we need to add a line break by ourselves.

And secondly, there is no need to add "\n" in out << old << "\n" << line;

Just change it to

out << old << line << "\n"; // line break at the end of each word is needed.

Hope it does your task. :)

OTHER TIPS

Just wanted to add somthing , if i use one word like Line1 , Line2 , line3 so the code will go on very well

Line1

Line2

Line3

but if I add more words in each line , I will get troubles , So I changed

while(in >> s) 

to

while(getline(in, s))   

In addition to Swapnil R Mehta Answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top