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

int main()
{
  ofstream wysla;
  wysla.open("wysla.txt", ios::app);
  int kaput;
  string s1,s2;
  cout<<"Please select from the List below"<<endl;
  cout<<"1.New entry"<<endl;
  cout<<"2.View Previous Entries"<<endl;
  cout<<"3.Delete an entry"<<endl;
  cin>>kaput;
  switch (kaput)
  {
    case 1:

      cout<<"Dear diary,"<<endl;
      getline(cin,s1);
      wysla<<s1;
      wysla.close();

      break;
   }
   return 0;
}

In this code I have tried to save a string of characters but it is not possible e.g,.. when I use getline nothing is saved on the text file when I use cin only the first word is saved. I would like to save the whole entry what do I do?

0

4 Answers 4

6

Use cin.ignore() after cin >> kaput; to remove \n from buffer.

cin >> kaput;
cin.ignore();

Extracts and discards characters from the input stream until and including delim.

As the comment, you'd better to use

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Sign up to request clarification or add additional context in comments.

3 Comments

I would use cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); because if the user had input 4 and then two spaces and then enter, this wouldn't work
good idea but in my main program wen i use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); it brings up some errors though the first answer works
@Wysla: If think to solve those errors you should #include <limits> because of std::numeric_limits.
0

You might need to insert a cin.ignore() after cin >> kaput to read the newline character at the end of the first input. Otherwise getline sees this newline as the first character, consumes it and ends reading.

Comments

0

When you enter the number, number will be read into kaput variable, but '\n' character will still be in the buffer, which will be read by getline). To resolve this issue you need to call cin.ignore() to remove newline character from the stdin buffer

Comments

0

This can work :

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

    int main() {
       string firstname;
       ofstream name;
       name.open("name");
       cout<<"Name? "<<endl;
       cin>>firstname;
       name<<firstname;
       name.close();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.